rust - `return 5;` 是 Rust 中的语句或表达式吗?

标签 rust

我不是吹毛求疵的,而是来自Statements and expressions :

We’ve actually already used statements and expressions. Statements are instructions that perform some action and do not return a value. Expressions evaluate to a resulting value. Let’s look at some examples.

......

Expressions do not include ending semicolons. If you add a semicolon to the end of an expression, you turn it into a statement, which will then not return a value. Keep this in mind as you explore function return values and expressions next.

那么对于return 5;,它是语句还是表达式?如果是语句,语句不应该有返回值;如果是表达式,则表达式不应有结束分号。

最佳答案

那里的措辞不准确。当它说“一条语句......不会返回一个值”时,这意味着一条语句不是通过将其评估为最终值(如表达式)来处理的,而是通过执行它来处理的。在 return 语句的情况下,执行采取退出当前函数的形式,将返回值传递给调用函数。

return 5; 肯定是一条语句。

关于rust - `return 5;` 是 Rust 中的语句或表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52475457/

相关文章:

rust - 常量 ìf` 表达式条件下的关联常量

rust - 由于需求冲突,无法推断出 autoref 的适当生命周期

rust - 有没有办法部分解构结构?

rust - 使用Rc <RefCell <.. >>实现二进制搜索树时的生命周期问题

rust - 匹配和解包之间的不同行为

rust - 如何将字符串写入文件?

sockets - 使用 Tokio futures 的多播 UDP 数据包

rust - 由于双重借用,无法将自身作为回调参数传递

enums - 如何找到枚举变体的参数数量?

rust - 将可迭代传递给函数并在 Rust 中迭代两次