Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

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 };
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...