From this tutorial:
An if without an else always results in () as the value.
Why does Rust impose this restriction and doesn't let an if
without an else
return other values, like this:
let y = if x == 5 { 10 };
From this tutorial:
An if without an else always results in () as the value.
Why does Rust impose this restriction and doesn't let an if
without an else
return other values, like this:
let y = if x == 5 { 10 };
For your example, the right question is: “What would the value of
y
be ifx
is not 5?”. What would happen here?You could think that the if-without-else-expression could return an
Option<_>
, but...Some()
&else { None }
)In Rust, nearly everything is an expression (with the exception of
let
-bindings and expressions ending with a semicolon, so called expression statements). And there are a few examples of expressions always returning()
, because nothing else makes sense. These include (compound-)assignments (why?), loops and if-without-else.