Style questionnaire: where would you put the semicolon or not at all?

A frequent piece of code in Rust would be:

Form 1 - no semicolons

if expr { return }

Form 2 - inner

if expr { return; }

Form 3 - all

if expr { return; };

Form 4 - outer

if expr { return };

For simple “guard” returns (usually you put things like this when you are checking the parameters/preconditions), all of the above are valid grammar.

(Assuming the value to return is (), and nothing required in the body other than return)

Which one do you prefer?

Mine: Form 4 (outer).

Form 2, but only for expressions that are divergent (like return) and/or result in (); otherwise Form 1.

This is exactly what I mean - the body contains only the return keyword.

Actually, I’d prefer to use

if !expr {/*rest  of code*/}

But jokes aside, I’d probably go for form 2, because I find that whenever I use return in rust, old C# coding habits creep up on me and it feels wrong to not put a semicolon there.

On the other hand, I feel that I need a separator after the simple statement…

I mean, in my rust-accustomed eyes, form 2 does feel weird to look at, but it feels more natural to type.

rustfmt gives

fn main() {
    if true {

and so that’s what I’d do.


Same. I automatically type ; after return, but for if I tend to use as little ; as I can get away with. So only if the result is assigned to something.

The problem of the inner style though, is that if you somehow want to refactor to

let value = if exp { return } else { v };

you have to move the semicolon out anyways.

rustfmt will give the “all” style if you already have an outside semicolon.

fn main() {
   if true {

It doesn’t matter whether or not there’s a semicolon after return. Adding an else clause doesn’t change this.


I know. But rustfmt will remove it for you.