Why is using return as the last statement in a function considered bad style?

Copied from reddit: Why isn’t the syntax of return statements explicit?


Answer from @pcwalton

Explicit return is really annoying in closures.
For example,
it was a major pain in JavaScript before ES6 arrow functions were introduced

myArray.map(function(x) { return x * 2; })

is gratuitously verbose, even without the function keyword.
Once you have implicit returns somewhere in your language,
you might as well have them everywhere for consistency’s sake.
The fact that it makes code less verbose is just an added bonus.

and from @mozilla_kmc

Rust is an expression-oriented language.
A block has the form

{
    stmt;
    stmt;
    ...
    stmt;
    expr
}

The statements are (basically) expressions or let bindings,
and the trailing expression is implicitly () if not specified.
The value of the whole block is the value of this last expression.

This is not just for functions. You can write

let foo = if x { y } else { z };

so if also takes the place of C’s ?: operator.
Every kind of block works the same way:

let result = unsafe {
    let y = mem::transmute(x);
    y.frob()
};

So the implicit return at the end of a function is a natural consequence
of Rust’s expression-oriented syntax.
The improved ergonomics are just a nice bonus 🙂

Puzzle: return x itself is an expression — what is its value?

Answer (suggested by @dubiousjim):

It is a never type !.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)