Skip to content

Definition of Option, and enum ordering #2634

Closed
rust-lang/rust
#87312
@lucas-deangelis

Description

@lucas-deangelis

In chapter 6.1, defining an enum, Option is described with Some(T) first and None later, while in Rust it's defined with None first and Some(T) later. This can break intuition when comparing enums. Here's the definition of Option in chapter 6.1:

This enum is Option, and it is defined by the standard library as follows:

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

However, this is not exact. The standard library defines Option this way:

#[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
#[rustc_diagnostic_item = "option_type"]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Option<T> {
    /// No value
    #[lang = "None"]
    #[stable(feature = "rust1", since = "1.0.0")]
    None,
    /// Some value `T`
    #[lang = "Some"]
    #[stable(feature = "rust1", since = "1.0.0")]
    Some(#[stable(feature = "rust1", since = "1.0.0")] T),
}

As you can see, None comes before Some(T). This has a consequence:

#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
enum MyOption<T> {
    Some(T),
    None,
}
fn main() {
    println!("{}", Option::None < Option::Some(0));
    println!("{}", MyOption::None < MyOption::Some(0));  
}
// => true
// => false

So with this, I would suggest reversing the current order of Option in the book to match with the one used in Rust.

I can make a PR for this, but I'd like to see if people are okay with the change first. I may be missing something.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions