Rust Program to Remove duplicate elements from ArrayList


Removes duplicate elements from an ArrayList.

Rust Programming Language


Removes duplicate elements from an ArrayList.


Problem


Rust program that removes duplicate elements from an ArrayList.

Input


use std::collections::HashSet;

fn remove_duplicates<T: std::cmp::Eq + std::hash::Hash + Clone>(list: &mut Vec<T>) {
    let set: HashSet<_> = list.iter().cloned().collect();
    list.clear();
    list.extend(set);
}

fn main() {
    let mut list = vec![1, 2, 2, 3, 4, 4, 4, 5];
    println!("Original list: {:?}", list);

    remove_duplicates(&mut list);
    println!("List after removing duplicates: {:?}", list);
}{codeBox}

Output


Original list: [1, 2, 2, 3, 4, 4, 4, 5]
List after removing duplicates: [1, 2, 3, 4, 5]{codeBox}

Explanation


This program defines a remove_duplicates function that takes a mutable reference to an ArrayList of type T that implements the Eq, Hash, and Clone traits. The function creates a HashSet from the elements of the input list and then clears the list and extends it with the unique elements from the set.

The main function creates an ArrayList of integers with some duplicate elements and prints the original list. It then calls remove_duplicates to remove the duplicates from the list and prints the resulting list.



Post a Comment