You can remove duplicates from a Vec in Rust by either sorting and using the built-in dedup method for in-place modification, or by using a HashSet to preserve the original order while filtering unique elements. The sorting approach is generally faster for large datasets where order doesn't matter, while the HashSet approach is necessary if you must maintain the sequence of first occurrences.
Here is the in-place method using sort and dedup. This is the most efficient approach if you don't care about the original order, as it modifies the vector directly without allocating a new collection.
fn main() {
let mut numbers = vec![3, 1, 2, 3, 4, 2, 1];
// Sort first so duplicates are adjacent
numbers.sort();
// Remove consecutive duplicates
numbers.dedup();
println!("{:?}", numbers); // Output: [1, 1, 2, 2, 3, 3, 4] -> wait, dedup removes consecutive,
// so after sort [1,1,2,2,3,3,4], dedup makes it [1,2,3,4]
}
If you need to preserve the original order of elements, use a HashSet to track seen items while building a new vector. This requires the elements to implement Hash and Eq.
use std::collections::HashSet;
fn main() {
let numbers = vec![3, 1, 2, 3, 4, 2, 1];
let mut seen = HashSet::new();
let mut unique = Vec::new();
for item in numbers {
if seen.insert(item) {
unique.push(item);
}
}
println!("{:?}", unique); // Output: [3, 1, 2, 4]
}
For a more functional style that preserves order, you can also use iter().copied().filter() combined with a mutable set, though the explicit loop above is often clearer and slightly more performant in tight loops. Note that dedup only removes consecutive duplicates, which is why sorting is a prerequisite for that specific method. If your vector contains complex types, ensure they implement PartialOrd for sorting or Hash/Eq for the set-based approach.