#![allow(unused)] fnmain() { leta = 8; letb: Vec<f64> = Vec::new(); let (a, c) = ("hi", false); }
以上都是语句,它们完成了一个具体的操作,但是并没有返回值,因此是语句。
由于 let 是语句,因此不能将 let
语句赋值给其它值,如下形式是错误的:
1 2 3 4
#![allow(unused)] fnmain() { letb = (leta = 8); }
错误如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
error: expected expression, found statement (`let`) // 期望表达式,却发现`let`语句 --> src/main.rs:2:13 | 2 | let b = let a = 8; | ^^^^^^^^^ | = note: variable declaration using `let` is a statement `let`是一条语句
error[E0658]: `let` expressions in this position are experimental // 下面的 `let` 用法目前是试验性的,在稳定版中尚不能使用 --> src/main.rs:2:13 | 2 | let b = let a = 8; | ^^^^^^^^^ | = note: see issue #53667 <https://github.com/rust-lang/rust/issues/53667> for more information = help: you can write `matches!(<expr>, <pattern>)` instead of `let <pattern> = <expr>`
以上的错误告诉我们 let
是语句,不是表达式,因此它不返回值,也就不能给其它变量赋值。但是该错误还透漏了一个重要的信息,let
作为表达式已经是试验功能了,也许不久的将来,我们在
stable rust 下可以这样使用。
1.2 表达式
表达式会进行求值,然后返回一个值。例如
5 + 2,在求值后,返回值
7,因此它就是一条表达式。
表达式可以成为语句的一部分,例如 let y = 2
中,2 就是一个表达式,它在求值后返回一个值
2(有些反直觉,但是确实是表达式)。