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
.
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With