user3071121
user3071121

Reputation: 643

Why don't we add a semicolon (;) at the end of if/else?

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");
};

Upvotes: 5

Views: 522

Answers (2)

Robin Lindner
Robin Lindner

Reputation: 605

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.

Upvotes: 1

Kornel
Kornel

Reputation: 100110

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

Upvotes: 1

Related Questions