Returning Result
In Rust, we have the std::result::Result
enum that works like Option
, but instead of saying we have it or we don't have it, the Result
type is more about saying we have it or we have this error. Just like Option
, Result
is an enum
type of the possible T
type or possible E
error:
enum Result<T, E> {
Ok(T),
Err(E),
}
Going back to the division by zero problem, take a look at the following simple example:
fn division(a: usize, b: usize) -> Result<f64, String> {
if b == 0 {
return Err(String::from("division by zero"));
}
return Ok(a as f64 / b as f64);
}
We don't want division by 0
, so we return an error for the preceding function.
Similar to Option
, Result
has many convenient features we can use. Suppose we have the we_have_it
and we_have_error...