let res = match is_42(23)
{
Ok(v) => {v},
Err(e) => {
// when there is an error, we print and return *early*
// stopping any further execution.
println!("Error : {:?}", e);
return;
}
};
// If there is an error, we never get here
println!("unwraped res : {:?}", res);
So, we never get to printing "unwraped res" when there is an error because we are explicitly returning out of the main function with the return keyword.
Now let's look at the second way:
// We want this to be done on errors
let fn_err_handling = |x| {
println!("Error msg: {:?}", x);
};
// What should `res` equal when there's an error ๐คจ ???
let res = is_42(23).map_err(fn_err_handling);
println!("unwraped res : {:?}", res);
The issue with this code is that execution will continue, even when there's an error, because the closure fn_err_handling can't return out of main, because it can only return out of itself.
In other words, what do you want res to equal if there happens to be an error?
If you want to unwrap the value and provide a fallback in the case of an error, you can use unwrap_or_else:
let fn_err_handling = |x| {
println!("Error msg: {:?}", x);
// We must return a value that can be used for
// res in the event of an error
0
};
let res = is_42(23).unwrap_or_else(fn_err_handling);
// This will print "unwrapped res : 0"
println!("unwraped res : {:?}", res);