OneBite.Dev - Coding blog in a bite size

Remove Duplicates From An Array In Rust

Code snippet for how to Remove Duplicates From An Array In Rust with sample and detail explanation

Rust is a highly efficient and reliable systems programming language that is suitable for a wide range of tasks. Its collection of unique characteristics makes it ideal for many programming functions, including the need to remove duplicates from arrays.

Code snippet for Removing Duplicates From An Array In Rust

Here is a simple example of how to remove duplicates from an array in Rust:

use std::collections::HashSet;

fn remove_duplicates(array: &[i32]) -> Vec<i32> {
    let mut uniques = HashSet::new();

    array.iter().filter(|&x| uniques.insert(*x)).cloned().collect()
}

fn main() {
    let array = [1, 2, 2, 3, 4, 4, 5, 5];
    let result = remove_duplicates(&array);
    
    println!("{:?}", result);
}

In the above script, the function ‘remove_duplicates’ is taking an array of i32. The result should return a vector array with no duplicate values.

Code Explanation for Removing Duplicates From An Array In Rust

Now, let’s break down the steps to provide a clear understanding of what’s happening within the code:

  1. First, Rust’s standard library’s HashSet is imported. A HashSet is a collection of data where every element is unique.

  2. Defining the function remove_duplicates, the array from your arguments is received as a parameter.

  3. Within remove_duplicates, a mutable uniques HashSet is initialized.

  4. The function iter() is called on the array parameter. This function returns each element in the array one at a time.

  5. filter() is a high-order function that receives a closure, where a boolean value is returned. If the value is true, the element is selected for the output. If the value is false, the element is discarded. In this context, the insert() function adds an element to the HashSet and returns a boolean: true if the value was added, and false if it was already in the HashSet. This way, only elements that are not in the HashSet pass the filter.

  6. cloned() is then used to clone the reference (&i32) to a real value (i32).

  7. Lastly, calling collect() wraps up all these unique i32 values into a new Vec, which is then returned by the function.

  8. Within the main function, a numeric array with duplicate values is declared, and our remove_duplicates function is invoked.

  9. The output is then printed using println!, which shows a vector array with no duplicates.

This simple yet robust Rust program effectively removes all duplicate elements from an array, demonstrating Rust’s efficiency and power when managing data structures.

rust