为什么选项的 Some 和 None 变体不需要限定?

Why don't Option's Some and None variants need to be qualified?

根据 docs for OptionOption 是一个具有变体 Some<T>None.

的枚举

为什么可以在不限定的情况下引用 SomeNone

例如,这很好用:

let x = Option::Some(5);
match x {
    Some(a) => println!("Got {}", a),
    None => println!("Got None"),
}

但是编译失败:

enum Foo<T> {
    Bar(T),
    Baz,
}
let x = Foo::Bar(5);
match x {
    Bar(a) => println!("Got {}", a),
    Baz => println!("Got Baz"),
}

编译器的错误是unresolved enum variant, struct or const `Bar`

自动插入到每个源文件中的 Rust prelude 包含此行:

pub use option::Option::{self, Some, None};

这将 Option 及其两个变体纳入范围。