我理解 Rust 中表达式和语句的概念,但是“The Rust Programming Language”一书中的一段代码让我感到困惑。
这是代码:
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {}", result);
}
Run Code Online (Sandbox Code Playgroud)
结果被分配了一个表达式(否则代码将不起作用)但后面的分号counter * 2让我认为这是一个语句。
作者在别处写道
表达式不包括结束分号。如果在表达式的末尾添加分号,则将其转换为语句,该语句不会返回值
有人可以为我澄清一下吗?
Rust 是一种面向表达式的语言。这意味着包括控制流结构在内的大多数结构都是表达式。后跟分号的表达式;是一个语句,其作用是计算表达式并丢弃其结果。因此,表达式和语句之间的区别不太重要。然而,一些表现分歧,这是一个有点怪异,如果你从其他语言。
break counter * 2是一个表达式。这个表达式的类型和值是什么?这是一个发散的表达。它没有值,类型是!没有值的类型。想象一下写:
let foo = break counter * 2;
Run Code Online (Sandbox Code Playgroud)
请问是什么类型的foo。不能有 的效果break,它本质上是一个 goto,同时还返回一个值并继续循环。break因此,表达式的类型始终是没有值的类型。一个无人居住的类型,一种没有任何值的类型,可能看起来很奇怪,但从概念上讲它很好。它是永远不会返回的函数的返回类型。这是无限循环的类型,永远无法计算出一个值。
是的,break counter * 2;是一个丢弃表达式值的语句break counter * 2,但表达式的值不是 counter * 2。
的类型是loop { ... }什么?按照规定,它是break循环中任何表达式中的表达式类型。的值loop必须来自break表达式之一。
所以,如果你添加一些类型:
fn main() {
// The type of counter is i32, because it is not
// suffixed with a different literal type, and no
// use below causes a different type to be inferred.
let mut counter: i32 = 0;
// The type of result is the type of the loop
// expression, which by definition is the type of
// the expressions passed to `break` within the
// loop. There is only one `break`, which is passed
// counter * 2, of type i32.
let result: i32 = loop {
counter += 1;
if counter == 10 {
// The type of this expression is !.
// Since a semicolon follows, the value
// is discarded, but the expression has no value.
break counter * 2;
}
};
println!("The result is {}", result);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |