Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

enums

rust

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.

like image 356
EFanZh Avatar asked Jun 25 '17 05:06

EFanZh


1 Answers

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};
like image 104
Francis Gagné Avatar answered Oct 19 '22 14:10

Francis Gagné