Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

rust - 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.

Why is it possible to refer to Some and None without qualifying them?

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`

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Rust prelude, which is automatically inserted into every source file, contains this line:

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

Which brings Option and both its variants in scope.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...