Last active
November 16, 2018 09:56
-
-
Save gyng/9ddd0048125cf42cd8db5ca7ec0a2a81 to your computer and use it in GitHub Desktop.
Sorting enums with anonymous structs in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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