To remove duplicates from an array in Rust, you can use the `iter` methods like `dedup` or `collect` with a `HashSet`.
In this example,
fn main() {
let mut numbers = vec![1, 2, 2, 3, 4, 4, 5];
numbers.dedup();
println!("Array without duplicates: {:?}", numbers);
}
Array without duplicates: [1, 2, 3, 4, 5]
In this example,
use std::collections::HashSet;
fn main() {
let colors = vec!["red", "green", "blue", "green", "yellow", "blue"];
let unique_colors: Vec<&str> = colors.into_iter().collect::<HashSet<&str>>().into_iter().collect();
println!("Array without duplicates: {:?}", unique_colors);
}
Array without duplicates: ["green", "yellow", "blue", "red"]
In this tutorial, we learned How to Remove Duplicates in an Array in Rust language with well detailed examples.