为什么不需要限定 Option 的 Some 和 None 变体? [英] Why don't Option's Some and None variants need to be qualified?
本文介绍了为什么不需要限定 Option 的 Some 和 None 变体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据文档Option
, Option
是一个带有 Some
和 None
变体的枚举.
According to the docs for Option
, Option
is an enum with variants Some<T>
and None
.
为什么可以在不限定的情况下引用 Some
和 None
?
Why is it possible to refer to Some
and None
without qualifying them?
例如,这很好用:
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`
推荐答案
Rustprelude,自动插入到每个源文件中,包含这一行:
The Rust prelude, which is automatically inserted into every source file, contains this line:
pub use option::Option::{self, Some, None};
它带来了 Option
及其范围内的两个变体.
Which brings Option
and both its variants in scope.
这篇关于为什么不需要限定 Option 的 Some 和 None 变体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文