Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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`

like image 319
krixon Avatar asked May 30 '15 13:05

krixon


People also ask

What is some and none in Rust?

The Option<T> enum has two variants: None , to indicate failure or lack of value, and. Some(value) , a tuple struct that wraps a value with type T .

What is Option <> in Rust?

Type Option represents an optional value: every Option is either Some and contains a value, or None , and does not. Option types are very common in Rust code, as they have a number of uses: Initial values. Return values for functions that are not defined over their entire input range (partial functions)


1 Answers

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.

like image 111
Levans Avatar answered Dec 21 '22 01:12

Levans