Errors

Learn how to handle errors in Rust.

Most languages handle errors through exceptions, but Rust does it with a type called Result<T, E>. It’s a data type with two generics: T and E. The T type on the left side is used for the return value, and the E is for the error. We need to return it with the Ok and Error function, respectively.

Press + to interact
// This is an example function that simply takes a parameter as string and return
// the expected type for "This works" or an error for everything else.
fn this_an_example(some_parameter: &str) -> Result<i32, String> {
match some_parameter {
"This works" => Ok(1),
&_ => Err("An Error".to_string())
}
}
fn main() {
println!("Result: {:#?}", this_an_example("This works"));
println!("Oh no!: {:#?}", this_an_example("Error"));
}

If we want to handle the result type, we use pattern matching. If we don’t ...