Skip to content

Definition of Option, and enum ordering #2634

Closed
rust-lang/rust
#87312

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.

Activity

  1. Lokathor commented on Mar 4, 2021

    @Lokathor

    There's an observable difference, but I would not say a significant difference. Still, if it helps things match the standard library it probably wouldn't hurt.

  2. lucas-deangelis commented on Mar 4, 2021

    @lucas-deangelis
    Author

    There's an observable difference, but I would not say a significant difference.

    I agree, maybe I wasn't clear enough about it but I don't say it's something big. Still, I wanted to document it as much as I can. The book is often how new people (me included!) learn Rust, and this change could look like trivial bikeshedding without a logical explanation behind it.

  3. added a commit that references this issue on Jul 20, 2021
    b41936b
  4. added a commit that references this issue on Mar 11, 2024
    f19baaf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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