Why does if (without) else always result in () as value?
1 answer
For your example, the correct question is "What is the value y
, if x
not 5?" What will happen here?
let x = 3;
let y = if x == 5 { 10 };
println!("{}", y); // what?!
You might think that an if-without-else statement might return Option<_>
, but ...
- this would mean that the main language depends on another library item (which is then called lang items) that everyone tries to avoid.
- You run into this situation too often.
- you can get the same behavior by adding a bit of code (
Some()
andelse { None }
)
In Rust, almost everything is an expression (with the exception of let
-bindings and expressions that end with a semicolon, so-called expression expressions). And there are some examples of expressions that always return ()
because nothing else makes sense. These include (compound) tasks ( why? ), Loops, and if-without-else.
+10
source to share