Sure, here is a Rust program to sort a vector of objects based on a specific property:
Rust
struct Person {
name: String,
age: i32,
}
fn sort_by_age(people: &mut Vec<Person>) {
people.sort_by(|a, b| a.age.cmp(&b.age));
}
fn main() {
let mut people = vec![
Person { name: "Alice".to_string(), age: 20 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 10 },
];
sort_by_age(&mut people);
println!("The people sorted by age:");
for person in people {
println!("{:?}", person);
}
}
This program first defines a struct called Person that has two properties:
name and age. The sort_by_age function takes a mutable reference to a
Vec of Person and sorts the vector by the age property. The
main function of the program creates a vector of Person objects and then calls the
sort_by_age function with the vector as input. The result of the function call is then printed to the console.
To run the program, you can save it as a file called sort_by_age.rs and then compile it using the following command:
Code snippet
rustc sort_by_age.rs
Once the program is compiled, you can run it using the following command:
Code snippet
./sort_by_age
This will print the following output to the console:
Code snippet
The people sorted by age:
Person { name: "Carol".to_string(), age: 10 }
Person { name: "Alice".to_string(), age: 20 }
Person { name: "Bob".to_string(), age: 30 }
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is a Rust program to sort a vector of objects based on a specific property:
Rust
This program first defines a struct called
Personthat has two properties:nameandage. Thesort_by_agefunction takes a mutable reference to aVecofPersonand sorts the vector by theageproperty. Themainfunction of the program creates a vector ofPersonobjects and then calls thesort_by_agefunction with the vector as input. The result of the function call is then printed to the console.To run the program, you can save it as a file called
sort_by_age.rsand then compile it using the following command:Code snippet
Once the program is compiled, you can run it using the following command:
Code snippet
This will print the following output to the console:
Code snippet