Cannot return a value from within an if in a match branch

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);

(Playground)

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);

(Playground)

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.

You need an explicit else:

if v % 2 == 0 {
    Ok(v + 1)
} else {
    Ok(v - 1)
}

Oh okay. Thank you very much.

You can only omit the return for the last line in an expression.

I think the missing else branch is the problem, adding return statements still has an error: Playground.

This seems like a nice place for a match guard:

    res = match res {
        Err(e) => Err(format!("Error in match: {}", e)),
        Ok(v) if v % 2 == 0 => Ok(v + 1),
        Ok(v) => Ok(v - 1),
    };
3 Likes

The playground link you provided doesn't work because the return type is implicitly (), while the Ok values returned are of type Result<{number}, String>.

This means that an else wouldn't work either, because that wasn't the only issue with the code.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.