You can sort a Vec in place using the .sort() method for simple types or .sort_by_key() for custom ordering, while .sorted() from the itertools crate or .into_iter().sorted() provides a non-destructive alternative. For most cases, mutating the original vector with .sort() is the most efficient approach as it avoids allocation.
Here is how to sort a vector of integers in ascending order in place:
fn main() {
let mut numbers = vec![3, 1, 4, 1, 5, 9, 2, 6];
// Sorts the vector in place
numbers.sort();
println!("{:?}", numbers);
// Output: [1, 1, 2, 3, 4, 5, 6, 9]
}
When dealing with complex types or needing custom logic (like sorting by a specific field or descending order), use .sort_by_key() or .sort_by(). For example, sorting a vector of structs by a field:
#[derive(Debug)]
struct User {
name: String,
age: u32,
}
fn main() {
let mut users = vec![
User { name: "Alice".to_string(), age: 30 },
User { name: "Bob".to_string(), age: 25 },
User { name: "Charlie".to_string(), age: 35 },
];
// Sort by age in ascending order
users.sort_by_key(|u| u.age);
// Sort by name in descending order
// users.sort_by(|a, b| b.name.cmp(&a.name));
println!("{:?}", users);
}
If you need to keep the original vector unchanged, you must clone it before sorting or use an iterator-based approach. Note that the standard library does not provide a direct .sorted() method on Vec that returns a new vector without cloning; you typically chain .clone() or use the itertools crate for a more ergonomic .sorted() method.
fn main() {
let numbers = vec![3, 1, 4, 1, 5];
// Clone first, then sort in place
let sorted = {
let mut temp = numbers.clone();
temp.sort();
temp
};
println!("Original: {:?}", numbers);
println!("Sorted: {:?}", sorted);
}
Remember that .sort() requires the elements to implement the Ord trait, while .sort_by() and .sort_by_key() allow you to define custom comparison logic for types that only implement PartialOrd or require specific extraction logic.