Skip to content

Instantly share code, notes, and snippets.

@gyng
Last active November 16, 2018 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gyng/9ddd0048125cf42cd8db5ca7ec0a2a81 to your computer and use it in GitHub Desktop.
Save gyng/9ddd0048125cf42cd8db5ca7ec0a2a81 to your computer and use it in GitHub Desktop.
Sorting enums with anonymous structs in Rust
use std::cmp::Ordering;
#[derive(Eq, Debug, PartialOrd, PartialEq)]
enum Foo {
A { val: i64 },
B,
}
// impl PartialEq for Foo {
// fn eq(&self, other: &Self) -> bool {
// match (self, other) {
// (_, Foo::B) => false,
// (Foo::B, _) => false,
// (Foo::A { val: l }, Foo::A { val: r }) => l == r,
// }
// }
// }
// impl PartialOrd for Foo {
// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
// match (self, other) {
// (_, Foo::B) => Some(Ordering::Less),
// (Foo::A { val: l }, Foo::A { val: r }) => l.partial_cmp(&r),
// (Foo::B, _) => Some(Ordering::Greater),
// }
// }
// }
impl Ord for Foo {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(_, Foo::B) => Ordering::Less,
(Foo::A { val: l }, Foo::A { val: r }) => l.cmp(&r),
(Foo::B, _) => Ordering::Greater,
}
}
}
fn main() {
let mut foos: Vec<Foo> = vec![Foo::B, Foo::A { val: 128 }, Foo::B, Foo::A { val: 256 }];
foos.sort();
println!("{:#?}", foos);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment