EFanZh
EFanZh

Reputation: 2436

Why can I use Ok and Err directly without the Result:: prefix?

For example:

enum Foobar {
    Foo(i32),
    Bar(i32),
}

fn main() {
    let a: Result<i32, i32> = Result::Ok(1);
    let b: Result<i32, i32> = Ok(1);
    let c: Foobar = Foobar::Foo(1);
    let d: Foobar = Foo(1); // Error!
}

I have to write Foobar::Foo() instead of just Foo(), but I can just write Ok() without Result::. Why is that? I have the same question for Some and None.

Upvotes: 13

Views: 885

Answers (1)

Francis Gagn&#233;
Francis Gagn&#233;

Reputation: 65832

A use item can add enum variants to a namespace, so that you don't have to prefix them by the enum's name.

use Foobar::*;

enum Foobar {
    Foo(i32),
    Bar(i32)
}

fn main() {
    let a: Result<i32, i32> = Result::Ok(1);
    let b: Result<i32, i32> = Ok(1);
    let c: Foobar = Foobar::Foo(1);
    let d: Foobar = Foo(1); // Not an error anymore!
}

The reason why Ok, Err, Some and None are available without qualification is that the prelude has some use items that add these names to the prelude (in addition to the enums themselves):

pub use option::Option::{self, Some, None};
pub use result::Result::{self, Ok, Err};

Upvotes: 17

Related Questions