I am reading Rust by Example book. In this example removing return
in Err(e) => return Err(e)
causes an error: expected `i32`, found enum `Result``
. Why is that?
What is the difference between Err(e) => return Err(e)
and Err(e) => Err(e)
?
Here is the code from the example:
use std::num::ParseIntError;
fn main() -> Result<(), ParseIntError> {
let number_str = "10";
let number = match number_str.parse::<i32>() {
Ok(number) => number,
Err(e) => return Err(e),
};
println!("{}", number);
Ok(())
}
let number = match number_str.parse::<i32>() {
Ok(number) => number,
Err(e) => return Err(e),
};
This says if number_str.parse::<i32>()
returns an Ok
to set number
to number
, an i32. If it returns an Err
to immediately return Err(e)
, which is a Result
, from main
, number
is not set.
That's fine because number
can only be an i32
and main
does return a Result
.
let number = match number_str.parse::<i32>() {
Ok(number) => number,
Err(e) => Err(e),
};
This says if number_str.parse::<i32>()
returns an Ok
to set number
to number
, an i32, same as before. If it returns an Err
to set number
to Err(e)
, which is a Result
.
number
cannot be both an i32
and a Result
, so you get a compiler error.