To remove duplicates from a vector in Rust, you can use the dedup
method or create a new vector with unique elements using a HashSet
.
In this example,
std::collections::HashSet
to use the HashSet
collection type.vec
with some integer values, including duplicates.HashSet
from the vector to filter out all duplicate elements. A HashSet
only keeps unique elements.HashSet
back to a vector using the into_iter
and collect
methods. This gives us a new vector containing only the unique elements.use std::collections::HashSet;
fn main() {
let vec = vec![1, 2, 2, 3, 4, 4, 4, 5, 6, 6];
let set: HashSet<_> = vec.into_iter().collect();
let unique_vec: Vec<_> = set.into_iter().collect();
println!("Vector after removing all duplicates: {:?}", unique_vec);
}
Vector after removing all duplicates: [1, 2, 3, 4, 5, 6]
In this example,
vec
with some integer values, including consecutive duplicates.dedup
method on vec
. This method removes consecutive duplicate elements from the vector, modifying it in place.dedup
method does not require any arguments and returns ()
.fn main() {
let mut vec = vec![1, 2, 2, 3, 4, 4, 4, 5, 6, 6];
vec.dedup();
println!("Vector after removing consecutive duplicates: {:?}", vec);
}
Vector after removing consecutive duplicates: [1, 2, 3, 4, 5, 6]
In this tutorial, we learned How to Remove Duplicates in a Vector in Rust language with well detailed examples.