5

In Rust, I have noticed that everything is an expression except 2 kinds of statements. Every expression that adds ; will become a statement. Rust's grammar wants statements to follow other statements.

So why don't we add ; at the end of an if / else "expression"? This is also an expression, so why don't we do this:

if true {
    println!("true");
} else {
    println!("false");
};
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user3071121
  • 605
  • 2
  • 8
  • 12
  • 2
    I don't know if you are going to get any clear, concise answers to *why* Rust allows this. It could just be "because it looks better" or "that's the way other similar languages do it". For what it's worth, you *can* put the `;` there, and I have when I use `if` / `else` as a ternary statement on one line. – Shepmaster Dec 27 '14 at 16:00
  • 1
    The semicolon can be omitted after an `if`, `while` or `match` expression if that expression is the "root" expression of a statement. – Francis Gagné Dec 28 '14 at 01:07
  • 2
    Discussed extensively on reddit http://www.reddit.com/r/rust/comments/2qjvzr/why_ifelse_expression_in_rust_doesnt_end_with_a/ – huon Dec 28 '14 at 04:32
  • @dbaupp the reddit post is mine. After I post my question in here and seems very little people pay attention to it. In fact, if you give more and more experiment with my question, you will find it's very confusing than the "look" it should be. – user3071121 Dec 28 '14 at 07:49
  • I am not sure why this question received downvotes and 4 closing votes. It is a very good question, and the answer on reddit is very nice and interesting. – Nemanja Boric Dec 29 '14 at 07:02

2 Answers2

1

The most common answer in the discussion is that it looks more like what users coming from other languages expect, and there is no harm in allowing that syntax (since the result type is () thanks to semicolons in the branches).

Kornel
  • 97,764
  • 37
  • 219
  • 309
1

I guess because it is a block expression in other languages like Java or Nginx-Conf a semicolon is only set after statements and not after blocks.

Robin Lindner
  • 515
  • 6
  • 13