|
| 1 | +## Sort a Vector of Structs |
| 2 | + |
| 3 | +[![std-badge]][std] [![cat-science-badge]][cat-science] |
| 4 | + |
| 5 | +Sorts a Vector of Person structs with properties `name` and `age` by its natural |
| 6 | +order (By name and age). In order to make Person sortable you need four traits [`Eq`], |
| 7 | +[`PartialEq`], [`Ord`] and [`PartialOrd`]. These traits can be siply derived. |
| 8 | +You can also provide a custom comparator function using a [`vec:sort_by`] method and sort only by age. |
| 9 | + |
| 10 | +```rust |
| 11 | +#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] |
| 12 | +struct Person { |
| 13 | + name: String, |
| 14 | + age: u32 |
| 15 | +} |
| 16 | + |
| 17 | +impl Person { |
| 18 | + pub fn new(name: String, age: u32) -> Self { |
| 19 | + Person { |
| 20 | + name, |
| 21 | + age |
| 22 | + } |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +fn main() { |
| 27 | + let mut people = vec![ |
| 28 | + Person::new("Zoe".to_string(), 25), |
| 29 | + Person::new("Al".to_string(), 60), |
| 30 | + Person::new("John".to_string(), 1), |
| 31 | + ]; |
| 32 | + |
| 33 | + // Sort people by derived natural order (Name and age) |
| 34 | + people.sort(); |
| 35 | + |
| 36 | + assert_eq!( |
| 37 | + people, |
| 38 | + vec![ |
| 39 | + Person::new("Al".to_string(), 60), |
| 40 | + Person::new("John".to_string(), 1), |
| 41 | + Person::new("Zoe".to_string(), 25), |
| 42 | + ]); |
| 43 | + |
| 44 | + // Sort people by age |
| 45 | + people.sort_by(|a, b| b.age.cmp(&a.age)); |
| 46 | + |
| 47 | + assert_eq!( |
| 48 | + people, |
| 49 | + vec![ |
| 50 | + Person::new("Al".to_string(), 60), |
| 51 | + Person::new("Zoe".to_string(), 25), |
| 52 | + Person::new("John".to_string(), 1), |
| 53 | + ]); |
| 54 | + |
| 55 | +} |
| 56 | + |
| 57 | +``` |
| 58 | + |
| 59 | +[`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html |
| 60 | +[`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html |
| 61 | +[`Ord`]: https://doc.rust-lang.org/std/cmp/trait.Ord.html |
| 62 | +[`PartialOrd`]: https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html |
| 63 | +[`vec:sort_by`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort_by |
0 commit comments