[rust-dev] RFC: Namespace enum variants under the enum

Patrick Walton pwalton at mozilla.com
Fri Mar 22 16:51:20 PDT 2013


Hi everyone,

It's been proposed that we place enum variants under the enum itself. 
That is:

     enum Option<T> {
         None,
         Some<T>,
     }

Would be accessed as:

     fn main() {
         let x = Option::None;
     }

The advantages of this are:

* Rust programmers very frequently generate ad-hoc prefixes to group 
variants under their namespaces. Prefixes seem to me to be the sincerest 
form of feature request for namespaces. (See Objective-C or Gecko 
`NSFoo`, GLib `g_`, etc.)

* You can get the old behavior with `use` or `pub use`.

* Other modules can import all variants belonging to an enum by simply 
writing (say) `use option::Option::*;`. This is a common thing to want 
and would, for example, eliminate all the `use obsolete::{ObsoleteFoo, 
ObsoleteBar, ...}` cruft in `parser.rs`. Note that Haskell introduced 
special notation for this into their `import` statements.

* C++11 went the direction of enum variant namespacing with `enum 
class`. I worry we may be making the same mistake that led them to 
introduce two incompatible versions of enums.

* This may clean up the `use core::option::Option` stuttering in the 
`option` module (and in a few related cases, like `std::list::List`). 
Instead of having types like `std::option::Option`, variants like 
`std::option::None`, and methods like `std::option::Option::is_none`, we 
could have simply `std::Option`, `std::Option::None`, and 
`std::Option::is_none` respectively. This seems to read nicer.

The disadvantages are:

* `::` will show up for many casual uses of enums. e.g.

     enum Color { Red, Green, Blue }
     fn main() {
         let x = Color::Red;
         match x {
             Color::Red => ...
             Color::Green => ...
             Color::Blue => ...
         }
     }

Thoughts? This would be a very late-stage change that will break pretty 
much all Rust code in existence, and it has disadvantages, but the 
advantages seem compelling enough to consider it...

Patrick


More information about the Rust-dev mailing list