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,name
andage
, both of typeString
andu8
respectively.let mut people = vec![...]
- creates a mutable vector ofPerson
structs.people.sort_by(|a, b| a.name.cmp(&b.name))
- sorts the vector ofPerson
structs by thename
field in ascending order using thesort_by
method. The closure passed tosort_by
takes two arguments,a
andb
, and compares thename
fields of each using thecmp
method.for person in people { ... }
- iterates over the sorted vector ofPerson
structs and prints out each person's name and age.
Helpful links
Related
- Example of struct private field in Rust
- How to get struct value in Rust
- Rust struct without fields
- How to update struct in Rust
- Example of struct with vector field in Rust
- Example of struct public field in Rust
- Example of struct of structs in Rust
- How to map struct in Rust
- How to generate struct from json in Rust
- How to serialize struct to json in Rust
More of Rust
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to use regex to match a group in Rust?
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to create a slice from a string in Rust?
- How to replace strings using Rust regex?
- Hashshet example in Rust
- How to create a HashSet from a Vec in Rust?
See more codes...