我在阅读 Rust 文档时遇到了以下示例和语句
使用返回作为函数的最后一行是可行的,但被认为是糟糕的风格:
fn foo(x: i32) -> i32 {
if x < 5 { return x; }
return x + 1;
}
我知道我可以把上面的写成
fn foo(x: i32) -> i32 {
if x < 5 { return x; }
x + 1
}
但我更倾向于写前者,因为它更直观。我确实理解函数返回值应该用作表达式,以便后面的工作,但是为什么不鼓励前者呢?
最佳答案
从 reddit 复制:Why isn't the syntax of return statements explicit?
来自 @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.
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
!
.
关于rust - 为什么将 return 用作函数中的最后一条语句被认为是错误的风格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27961879/