相关疑难解决方法(0)

为什么使用return作为函数中的最后一个语句被认为是错误的样式?

我正在阅读Rust文档,并遇到了以下示例和声明

使用return作为函数的最后一行有效,但被认为是糟糕的样式:

fn foo(x: i32) -> i32 {
    if x < 5 { return x; }

    return x + 1;
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以写上面的内容

fn foo(x: i32) -> i32 {
    if x < 5 { return x; }

    x + 1
}
Run Code Online (Sandbox Code Playgroud)

但我更倾向于写前者,因为这更直观.我确实理解函数返回值应该用作表达式,以便后面有效但是为什么不鼓励前者呢?

rust

18
推荐指数
4
解决办法
4482
查看次数

标签 统计

rust ×1