Closed
Description
The documentation for the Ord
and PartialOrd
traits says:
When
derive
d 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