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(())
}
This says if
number_str.parse::<i32>()
returns anOk
to setnumber
tonumber
, an i32. If it returns anErr
to immediately returnErr(e)
, which is aResult
, frommain
,number
is not set.That's fine because
number
can only be ani32
andmain
does return aResult
.This says if
number_str.parse::<i32>()
returns anOk
to setnumber
tonumber
, an i32, same as before. If it returns anErr
to setnumber
toErr(e)
, which is aResult
.number
cannot be both ani32
and aResult
, so you get a compiler error.