Why if/else expression in Rust doesn't end with a ;?


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

My very limited understanding is as follows: While if true { a(); } else { b(); } is technically an expression, it’s almost like a statement since the value of the expression { a(); } is unit: (). So while you can put a semicolon at the end, it doesn’t really make sense to add that bit of syntactic noise.

I think that anywhere an expression has type () and ends in }, the closing brace can ends the statement instead of requiring a semicolon, for convenience.


This has been extensively discussed on Reddit: http://www.reddit.com/r/rust/comments/2qjvzr/why_ifelse_expression_in_rust_doesnt_end_with_a/

(BTW, it’s generally polite to post a question to one place and then just link from any other places, rather than posting completely separately in 2 (3?) places. Or at least mention the cross-posting at each place. :smile:)


I really apologize for my impoliteness. I don’t know that. If you know how to close this topic please let me know. I will close it as soon as I know how to do that.


It’s not a problem: the downside of having threads in multiple locations is the discussion becomes fragmented and some people miss out, but that didn’t happen much here.


I read the reddit discussion, but still feel like I don’t entirely understand the rules. This is as opposed to C (for example), where I feel like I have a perfect understanding of how semicolons work, where they’re allowed, etc.

If would be nice if there was a concise rule or explanation for us newbies to chew on.

So far, my theory is that a semicolon is not a statement separator in Rust, nor does Rust have an “expression statement” like C. Beyond that, I’m just winging it, which feels uncomfortable.

closed #7

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.