Skip to content

Misleading documentation for derived Ord/PartialOrd implementation for enums #75620

Closed
@robinkrahl

Description

@robinkrahl

The documentation for the Ord and PartialOrd traits says:

When derived on enums, variants are ordered by their top-to-bottom declaration order.

But apparently, the derived implementation actually orders the variants by their discriminant. The discriminants do not necessarily match the declaration order.

I tried this code (gist, Rust Playground):

#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
enum A {
    V1,
    V2,
}

#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
#[repr(u8)]
enum B {
    V1 = 1,
    V2 = 0,
}

fn main() {
    let mut a = vec![A::V1, A::V2];
    let mut b = vec![B::V1, B::V2];
    a.sort();
    b.sort();
    println!("a = {:?}", a);
    println!("b = {:?}", b);
}

Both enums have the same declaration order, so the output should be:

a = [V1, V2]
b = [V1, V2]

Instead, this happened:

a = [V1, V2]
b = [V2, V1]

Meta

$ rustc --version --verbose
rustc 1.45.2 (d3fb005a3 2020-07-31)
binary: rustc
commit-hash: d3fb005a39e62501b8b0b356166e515ae24e2e54
commit-date: 2020-07-31
host: x86_64-unknown-linux-gnu
release: 1.45.2
LLVM version: 10.0

Reproduced with both the stable and the nightly compiler on the Rust Playground

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-bugCategory: This is a bug.E-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions