rustHow to sort a struct in Rust
Sorting a struct in Rust can be done using the sort_by method on a vector of structs. This method takes a closure as an argument which defines the sorting criteria. The example code below sorts a vector of structs by the name field in ascending order.
struct Person {
name: String,
age: u8,
}
let mut people = vec![
Person { name: "John".to_string(), age: 30 },
Person { name: "Alice".to_string(), age: 20 },
Person { name: "Bob".to_string(), age: 25 },
];
people.sort_by(|a, b| a.name.cmp(&b.name));
for person in people {
println!("{} is {} years old", person.name, person.age);
}
Output example
Alice is 20 years old
Bob is 25 years old
John is 30 years old
Code explanation
struct Person- defines a struct with two fields,nameandage, both of typeStringandu8respectively.let mut people = vec![...]- creates a mutable vector ofPersonstructs.people.sort_by(|a, b| a.name.cmp(&b.name))- sorts the vector ofPersonstructs by thenamefield in ascending order using thesort_bymethod. The closure passed tosort_bytakes two arguments,aandb, and compares thenamefields of each using thecmpmethod.for person in people { ... }- iterates over the sorted vector ofPersonstructs and prints out each person's name and age.
Helpful links
Related
- How to init zero struct in Rust
- Example of Rust struct with closure
- Example of constant struct in Rust
- Example of struct private field in Rust
- How to serialize struct to xml in Rust
- Example of bit field in Rust struct
- Rust struct without fields
- Example of struct with vector field in Rust
- How to update struct in Rust
- How to convert struct to bytes in Rust
More of Rust
- How to make regex case insensitive in Rust?
- How to replace a capture group using Rust regex?
- How to use regex lookahead in Rust?
- How to perform matrix operations in Rust?
- How to ignore case in Rust regex?
- How to use 'or' in Rust regex?
- How to use regex to match a double quote in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
- Yield example in Rust
- How to convert a u8 slice to a hex string in Rust?
See more codes...