为什么在一个被认为是糟糕风格的函数中使用 return 作为最后一个语句? [英] Why is using return as the last statement in a function considered bad style?
问题描述
我在阅读 Rust 文档时遇到了以下示例和语句
I was reading through the Rust documentation and came across the following example and statement
使用 return 作为函数的最后一行有效,但被认为是糟糕的风格:
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?
推荐答案
It just is.
约定不需要特别好的理由,他们只需要被普遍接受的约定.碰巧,这个确实有一个比较好的理由——它更短,因为你没有 return
和 ;
.你可能认为 return x + 1;
更直观,但我强烈反对——它真的很令人讨厌,我觉得有必要修复它.我这样说的人,在开始使用 Rust 之前,从来没有使用过面向表达式的语言.写Python的时候,在那个地方return x + 1
看起来是对的,而写Rust的时候就错了.
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 that return 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:
fn foo(x: i32) -> i32 {
if x < 5 {
x
} else {
x + 1
}
}
这强调了语言的表达取向.
This emphasises the expression orientation of the language.
这篇关于为什么在一个被认为是糟糕风格的函数中使用 return 作为最后一个语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!