简体   繁体   English

为什么Option的Some和None变体不需要合格?

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

According to the docs for Option , Option is an enum with variants Some<T> and None . 根据Option文档Option是一个包含变量Some<T>None的枚举。

Why is it possible to refer to Some and None without qualifying them? 为什么可以在没有资格的情况下引用SomeNone

For example, this works fine: 例如,这工作正常:

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

But this fails to compile: 但这无法编译:

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

The error from the compiler is unresolved enum variant, struct or const `Bar` 编译器的错误是unresolved enum variant, struct or const `Bar`

The Rust prelude , which is automatically inserted into every source file, contains this line: Rust prelude (自动插入到每个源文件中)包含以下行:

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

Which brings Option and both its variants in scope. 这带来了Option及其变体的范围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我们不需要在某些rust迭代器中从Result提取值? - Why don't we need to extract values from Result in some rust iterators? 在已知不是“无”的情况下,可以使用“ let Some(var)= option;`”语法吗? - Can the `let Some(var) = option;` syntax be used in a situation where it's known that it's not `None`? 为什么不能为通用选项克隆 None<t> 当 T 不实现克隆?</t> - Why can't None be cloned for a generic Option<T> when T doesn't implement Clone? 为什么在返回类型选项时返回 None<T> 当 T 不是引用时不返回空指针 - Why is returning None when of return type option<T> not return the null pointer when T is not a reference 为什么我们需要为 Option 调用 take()<t> 多变的</t> - why do we need to call take() for Option<T> variable 为什么不能在比赛武器中推断出枚举变体? - Why can't enum variants be inferred in match arms? 为什么在 Rust 中的表达式在 Option.and 被评估,如果选项是无? - Why is in Rust the expression in Option.and evaluated, if option is None? 如何在任何 scope 访问“选项”中的“部分”和“无”? - How are "Some" and "None" from "Option" accessible at any scope? 为什么 &Option 上的模式匹配<t>产生 Some(&T) 类型的东西?</t> - Why does pattern matching on &Option<T> yield something of type Some(&T)? 当引用不需要时,为什么原始指针需要 const 关键字? - Why do raw pointers need the const keyword when references don't?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM