Why if without else is a type mismatch error?


#1

Can someone explain why this function contains an error:

fn g(condition: bool) -> &'static str {
    if condition { "true" }
    "false"
}

but the following one works?

fn g(condition: bool) -> &'static str {
    if condition { "true" }
    else { "false" }
}

Error:

rustc 1.16.0 (30cf806ef 2017-03-10)
error[E0308]: mismatched types
 --> <anon>:7:9
  |
7 |         "true"
  |         ^^^^^^ expected (), found reference
  |
  = note: expected type `()`
             found type `&'static str`

Link to playground

Thank you.


#2

Just forgot a return inside the if… sorry for the noise.


#3

The whole if is an expression, and each expression in Rust must have a single type. You cannot have different types on the if branch and the else branch, that would be incoherent.

In your second example (the one that works) each branch of the if returns &str, so it works.
However, in your first example the if branch returned &str and the missing else branch returned ().