rust - 为什么将 return 用作函数中的最后一条语句被认为是错误的风格?

标签 rust

我在阅读 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.

来自@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 !.

关于rust - 为什么将 return 用作函数中的最后一条语句被认为是错误的风格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27961879/

相关文章:

rust - 返回对 Arc 和 Mutex 后面的值的可变引用

rust - 为什么调用者必须使用构造函数而不是直接创建结构?

rust - 链表实现中的引用

json - 使用 BufReader 在 Rust 中读取 JSON 文件时出错:特征绑定(bind)结果:std::io::Read 不满足

rust - `iter().map().sum()` 和 `iter().fold()` 一样快吗?

string - Rust 中有没有像 JavaScript 的 substr 这样的方法?

rust - 使用谓词返回引用时存在生命周期冲突(使用谓词实现 “split at mut”)

rust - 重用 `thiserror` 定义中的错误消息

rust - 添加和+之间的区别?

rust - 在 rust 中处理具有各种表示形式的枚举的规范方法