A Note on Semicolons

If you remember back from Anatomy of Rust, we said that any expression can be converted into an expression statement by putting a semicolon at the end. That’s what happens with all of our println! macro calls. The println! part is an expression; following it with a semicolon turns it into a statement. But if you look at the example above, I never put a semicolon after the if expression. Technically, you can put them there if you want, but that’s not a recommended style in Rust.

There’s one other rule about expression statements that I didn’t mention previously. If you have a block-like expression (such as an if expression), and if that expression evaluates to unit, you’re allowed to leave off the semicolon. We’ve actually been doing that in a lot of examples already, but just haven’t talked about it. For example, we’ve seen code like this with blocks quite a bit:

Get hands-on with 1200+ tech skills courses.