OneBite.Dev - Coding blog in a bite size

Find The Common Elements In Two Arrays In Rust

Code snippet for how to Find The Common Elements In Two Arrays In Rust with sample and detail explanation

Finding common elements in two arrays is a fundamental task in any programming language, which often comes up in contexts such as data analysis, and algorithm development. In this article, we’ll demonstrate a simple way to tackle this task using Rust, an increasingly popular language known for its performance and safety.

Code Snippet: Finding Common Elements in Rust

fn main() {
    let arr1 = [1, 2, 3, 4, 5];
    let arr2 = [4, 5, 6, 7, 8];

    let common: Vec<i32> = arr1.iter().filter(|&num| arr2.contains(num)).cloned().collect();

    println!("{:?}", common);
}

Code Explanation for Finding Common Elements in Rust

Let’s break down the code to understand it better.

  1. We’re defining two arrays arr1 and arr2 which contain 5 elements each. We’ll find the common elements in these two arrays.
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [4, 5, 6, 7, 8];
  1. We use the filter method to identify the common elements. filter is a method provided by Rust that applies a specified function or condition to each item in an array and returns an array that contains items where the provided function will return true.

  2. We create a closure |&num| arr2.contains(num) which will check whether each number in arr1 exists in arr2 or not.

  3. filter method will return an iterator, but we need to turn it back into a collection. So, we will use cloned method, which creates a copy of value and then collect method to get our result as a vector.

let common: Vec<i32> = arr1.iter().filter(|&num| arr2.contains(num)).cloned().collect();
  1. Finally, we are printing the common elements using println!.
println!("{:?}", common);

That’s all! Run the program, and you will see [4,5] printed to the console, which are the common elements in arr1 and arr2. This approach is perfect for finding common elements in two arrays containing a smaller number of elements. However, for larger arrays, an optimized approach using hashsets would be recommended.

In this tutorial, you’ve learned how to find common elements of two arrays in Rust language using the filter method. Happy coding!

rust