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

For instance:

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 need to write Foobar::Foo() instead of Foo() , but I can just write Ok() without Result:: . Why is this? I have the same question for Some and None .

+5
source share
1 answer
Element

A use can add enumeration options to the namespace, so you do not need to prefix them with the enumeration 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 Ok , Err , Some and None are available without qualification is because the prelude has several use elements that add these names to the prelude (in addition to the enumerations themselves):

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

Source: https://habr.com/ru/post/1269187/


All Articles