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

前端 未结 1 614
终归单人心
终归单人心 2021-01-19 01:55

From this tutorial:

An if without an else always results in () as the value.

Why does Rust impose this restriction and doesn\'

相关标签:
1条回答
  • 2021-01-19 02:48

    For your example, the right question is: “What would the value of y be if x is not 5?”. What would happen here?

    let x = 3;
    let y = if x == 5 { 10 };
    println!("{}", y);  // what?!
    

    You could think that the if-without-else-expression could return an Option<_>, but...

    1. this would mean that the core language depends on yet another library item (those are then called lang items) which everyone tries to avoid
    2. you don't run into this situation too often
    3. you can get the same behavior by adding only a little bit of code (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.

    0 讨论(0)
提交回复
热议问题