分号在 Rust 中是可选的吗? [英] Are semicolons optional in Rust?

查看:40
本文介绍了分号在 Rust 中是可选的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

既然分号在 Rust 中显然是可选的,为什么,如果我这样做:

Since semicolons are apparently optional in Rust, why, if I do this:

fn fn1() -> i32 {    
    let a = 1
    let b = 2
    3
}

我收到错误:

error: expected one of `.`, `;`, `?`, or an operator, found `let`
 --> src/main.rs:3:9
  |
2 |         let a = 1
  |                  - expected one of `.`, `;`, `?`, or an operator here
3 |         let b = 2
  |         ^^^ unexpected token

推荐答案

它们不是可选的.分号会修改表达式语句的行为,因此对于一行代码是否使用分号应该是一个有意识的决定.

They're not optional. Semicolons modify the behaviour of an expression statement so it should be a conscious decision whether you use them or not for a line of code.

在 Rust 中几乎所有的东西都是一个表达式.表达式是返回值的东西.如果你加了一个分号,你就是在抑制这个表达式的结果,这在大多数情况下是你想要的.

Almost everything in Rust is an expression. An expression is something that returns a value. If you put a semicolon you are suppressing the result of this expression, which in most cases is what you want.

另一方面,这意味着如果您以不带分号的表达式结束函数,则将返回最后一个表达式的结果.这同样适用于 match 语句中的块.

On the other hand, this means that if you end your function with an expression without a semicolon, the result of this last expression will be returned. The same can be applied for a block in a match statement.

您可以在任何其他需要值的地方使用不带分号的表达式.

You can use expressions without semicolons anywhere else a value is expected.

例如:

let a = {
    let inner = 2;
    inner * inner
};

这里的表达式 inner *inner 不以分号结尾,所以它的值没有被抑制.由于它是块中的最后一个表达式,它的值将被返回并赋值给 a.如果在同一行上加分号,则不会返回 inner *inner 的值.

Here the expression inner * inner does not end with a semicolon, so its value is not suppressed. Since it is the last expression in the block, its value will be returned and assigned to a. If you put a semicolon on this same line, the value of inner * inner won't be returned.

在您的特定情况下,不抑制 let 语句的值是没有意义的,并且编译器正确地为您提供了一个错误.事实上,let 不是一个表达式.

In your specific case, not suppressing the value of your let statement doesn't make sense, and the compiler is rightly giving you an error for it. In fact, let is not an expression.

这篇关于分号在 Rust 中是可选的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆