发散
发散表达式是永不完成正常执行的表达式。
#![allow(unused)]
fn main() {
fn diverges() -> ! {
panic!("This function never returns!");
}
fn example() {
let x: i32 = diverges(); // This line never completes.
println!("This is never printed: {x}");
}
}
有关特定表达式发散行为,请参阅以下规则:
- expr.block.diverging — 块表达式。
- expr.if.diverging —
if表达式。 - expr.loop.block-labels.type — 带
break的标记块表达式。 - expr.loop.break-value.diverging — 带
break的loop表达式。 - expr.loop.break.diverging —
break表达式。 - expr.loop.continue.diverging —
continue表达式。 - expr.loop.infinite.diverging — 无限
loop表达式。 - expr.match.diverging —
match表达式。 - expr.match.empty — 空
match表达式。 - expr.return.diverging —
return表达式。 - type.never.constraint — 返回
!的函数调用。
Note
panic!宏和相关的生成 panic 的宏(如unreachable!)也具有类型!并且是发散的。
任何类型为 ! 的表达式都是发散表达式。然而,发散表达式不限于类型 !;其他类型的表达式也可能发散(例如,Some(loop {})的类型为Option<!>`)。
Note
虽然
!被认为是无人居住的类型,但类型无人居住不足以使其发散。#![allow(unused)] fn main() { enum Empty {} fn make_never() -> ! {loop{}} fn make_empty() -> Empty {loop{}} fn diverging() -> ! { // This has a type of `!`. // So, the entire function is considered diverging. make_never(); // OK: The type of the body is `!` which matches the return type. } fn not_diverging() -> ! { // This type is uninhabited. // However, the entire function is not considered diverging. make_empty(); // ERROR: The type of the body is `()` but expected type `!`. } }
Note
发散可以传播到周围的块。参见 expr.block.diverging。
回退
如果要推断的类型仅与发散表达式统一,则该类型将被推断为 !。
Example
#![allow(unused)] fn main() { fn foo() -> i32 { 22 } match foo() { // ERROR: The trait bound `!: Default` is not satisfied. 4 => Default::default(), _ => return, }; }
2024 Edition differences
在 2024 版本之前,该类型被推断为
()。
Note
重要的是,类型统一可能是结构化发生的,因此回退
!可能是更大类型的一部分。以下代码可以编译:#![allow(unused)] fn main() { fn foo() -> i32 { 22 } // This has the type `Option<!>`, not `!` match foo() { 4 => Default::default(), _ => Some(return), }; }