Why does if (without) else always result in () as value?

From this tutorial :

If if without else always results in () as value.

Why does Rust impose this restriction and not allow other values to if

be else

returned without returning, for example:

let y = if x == 5 { 10 };

      

+3


source to share


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

    and else { 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







All Articles