Reputation: 360
The purpose of this code is to loop from 1 to 4 and stop. My question is why if I add or leave the semicolon in the else statement (;) it doesn't matter... the code compile just fine. What's the best approach? Add the semicolon or leave it?
fn main() {
let mut var = 1;
loop{
println!("It is now {}", var);
if var >= 4 {
println!("Finished the loop");
break;
} else {
var = var + 1;
}
}
}
Upvotes: 3
Views: 831
Reputation: 601351
In general, the trailing semicolon determines the return value of the block. If you leave the semicolon out, the return value is the value of the last expression in the block. With the semicolon included, the return value is always Rust's unit value, the empty tuple ()
(except when the block contains an expression that does not return, in which case the return type is the "never" type !
, which does not have any values).
In this particular case, there is no semantic difference. Assignment expressions return the unit value as well, i.e. (var = var + 1) == ()
. However, this is more or less a coincidence. You don't actually want to return any value in that statement, so including the semicolon makes your intention much clearer.
Upvotes: 6
Reputation: 382092
The generated binary will be exactly be the same here but don't just think about the compiler, think about the humans reading the code too.
The absence of a semicolon at the end of the last statement of a block has an implied meaning: the value is returned from the block, the value matters.
If the value isn't used, don't return it. Put that semicolon to help humans read the code.
If you don't put that semicolon and configure Clippy to be very annoying, you'll get a warning too due to the semicolon_if_nothing_returned rule.
Upvotes: 3