Search CTRL + K

Never Type

在 rust 中有一个叫 ! 的特殊类型,叫 never type(类型理论中称为 empty type),它不能用于创建值,只能用于在函数不返回时充当返回值。

不返回的函数称为 发散函数(diverging functions)

这个类型有什么用?事实上,continuepanic! 等都是返回值为 !,因此可以在 match 等语句中使用而不会导致返回类型不匹配:

let value = match self {
    Some(1) => 1,
    None => panic!("called `Option::unwrap()` on a `None` value"),

What is never type?

Rust has a special type named ! that’s known in type theory lingo as the empty type because it has no values. We prefer to call it the never type because it stands in the place of the return type when a function will never return.[1]

What is diverging functions?

fn bar() -> ! {
    // --snip--

This code is read as “the function bar returns never.” Functions that return never are called diverging functions.

  1. ↩︎