The Rust Language Reference on Expression Statements:
An expression statement is one that evaluates an expression and ignores its result. As a rule, an expression statement's purpose is to trigger the effects of evaluating its expression.
An expression that consists of only a block expression or control flow expression, if used in a context where a statement is permitted, can omit the trailing semicolon.
I imagine this is purely for aesthetics and ergonomics, since almost everything is an expression in Rust. If the trailing semicolon was mandatory after all expressions then we'd have to terminate if-else blocks (which are also expressions) with semicolons which looks terrible:
if {
// do something
} else {
// do something else
}; // <- gross
Similarly, we can omit the trailing semicolon on all control flow expressions because they produce control flow, so the typical function of the semicolon, which is to discard the expression's result and evaluate to ()
instead, becomes irrelevant.
fn five() -> i32 {
return 5 // to semicolon or not to semicolon? it doesn't matter
}
In the above example it doesn't make a difference if we terminate return 5
with a semicolon or not since nothing can "capture" the result of that expression anyway since it produces control flow. Same would be true for other control flow expressions like break
and continue
.