I have a result which I would like unpack using match
and then set the new value of by returning a value from match
.
I can do this in a simple example:
let mut res = Ok(5);
res = match res {
Err(e) => Err(format!("Error in match: {}", e)),
Ok(v) => Ok(v - 1),
};
println!("res={:?}", res);
However if I want to add an if
statement into the match
branch, and then return a value, I cannot. I get an error saying the expected return type is ()
not Result<foo, bar>
.
As seen in here:
let mut res = Ok(5);
// Increment if even, decrement if odd
res = match res {
Err(e) => Err(format!("Error in match: {}", e)),
Ok(v) => {
if v % 2 == 0 {
Ok(v + 1) // <<< Error here
}
Ok(v - 1)
}
};
println!("res={:?}", res);
Why is this? How can I return a value from the second example in the way I want? I suspect there is a way to do this, but I am not going about it correctly.