Why is the compiler asking me to add a return statement here?

Viewed 161

I'm trying to do the rustlings course and I don't understand the error I'm getting for the following code:

pub fn bigger(a: i32, b: i32) -> i32 {
    if a > b {
        a
    }
    b
}

Error:

error[E0308]: mismatched types
 --> exercises/if/if1.rs:7:9
  |
6 | /     if a > b {
7 | |         a
  | |         ^ expected `()`, found `i32`
8 | |     }
  | |_____- expected this to be `()`
  |
help: you might have meant to return this value
  |
7 |         return a;
  |         ^^^^^^  ^

if I add the return, it does work but shouldn't the above also work? If I use an if-else it works also:

pub fn bigger(a: i32, b: i32) -> i32 {
    if a > b {
        a
    } else {
        b
    }
}
1 Answers

In rust only the last expression is taken as return value.

In your case:

if a > b {
    a
}

and:

b

are expressions themselves, so which one should it return? In fact if expressions without and else clause return () in rust (that is why the conflict in types you get). For more reference refer to this answer.

Meanwhile:

if a > b {
    a
} else {
    b
}

is a single expression, which branches are single expressions too (a and b). So it is clear that it should return what the inner return of the if expressions does.

Also, you can use a return statement in the if expression to help the compiler realize what to do in the first case (From @Cerberus comments: return x is an expression, too - it just evaluates to never and so can be used everywhere without type mismatch.):

pub fn bigger(a: i32, b: i32) -> i32 {
    if a > b {
        return a;
    }
    b
}

Just the last b expression would be used as final return (other returns are statements not expressions).

Related