Skip to content

Instantly share code, notes, and snippets.

@kenta-s
Last active December 27, 2020 07:26
Show Gist options
  • Save kenta-s/efc22b2889eb1207cc279d04bc28485a to your computer and use it in GitHub Desktop.
Save kenta-s/efc22b2889eb1207cc279d04bc28485a to your computer and use it in GitHub Desktop.
// let's say there is a Struct named `Person` and you want to sort vector of that structs by a float field.
use std::cmp::Ordering;
struct Person {
name: String,
height: u32
}
impl PartialEq for Person {
fn eq(&self, other: &Self) -> bool {
self.height == other.height
}
}
impl PartialOrd for Person {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.height.partial_cmp(&other.height)
}
}
fn main() {
let mut people = Vec::new();
let alice = Person { name: String::from("Alice"), height: 168.0 as u32 };
let bob = Person { name: String::from("Bob"), height: 186.2 as u32 };
let carol = Person { name: String::from("Carol"), height: 172.1 as u32 };
people.push(alice);
people.push(bob);
people.push(carol);
people.sort_by(|a, b| a.partial_cmp(b).unwrap());
for person in people {
println!("{}", person.name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment