I was reading through the Rust documentation and came across the following example and statement
Using a return as the last line of a function works, but is considered poor style:
fn foo(x: i32) -> i32 {
if x < 5 { return x; }
return x + 1;
}
I know I could have written the above as
fn foo(x: i32) -> i32 {
if x < 5 { return x; }
x + 1
}
but I am more tempted to write the former, as that is more intuitive. I do understand that the function return value should be used as an expression so the later works but then why wouldn't the former be encouraged?
Copied from reddit: Why isn't the syntax of return statements explicit?
Answer from @pcwalton
and from @mozilla_kmc
It just is.
Conventions don’t need to have particularly good reasons, they just need to be generally accepted conventions. As it happens, this one does have a comparatively good reason—it’s shorter as you don’t have the
return
and;
. You may think thatreturn x + 1;
is more intuitive, but I disagree strongly—it really grates and I feel a compelling need to fix it. I say this as one who, before starting using Rust, had never used an expression-oriented language before. While writing Python,return x + 1
in that place looks right, while writing Rust it looks wrong.Now as it happens, that code should probably be written thus instead:
This emphasises the expression orientation of the language.
The clippy lint gives the following rational for the
needless_return
lint:This is probably as good as an objective rationale as we will ever get.
As far as intuition goes; I feel that it is shaped by our individual experiences and therefore subjective. While Rust is not a functional programming language itself, many people using and developing it seem to have a strong background in functional programming languages like Haskell, which are entirely based on expressions. The influence can be strongly felt in many areas of Rust (e.g. error handling). So for them (and to be honest, myself included) using an expression instead of a statement seems more elegant.