OneBite.Dev - Coding blog in a bite size

Search For A Specific Element In An Array In Rust

Code snippet for how to Search For A Specific Element In An Array In Rust with sample and detail explanation

Searching for a specific element within an array can be achieved using various methods in the Rust programming language. In the following discourse, we’ll examine an easy and straightforward approach to accomplish this task using a piece of example code.

Code snippet: Searching for an Element in an Array in Rust

Here is a simple code snippet that shows how to search for an element in an array in Rust.

fn main() {
    let array = [10, 20, 30, 40, 50];
    let target = 30;

    let position_option = array.iter().position(|&x| x == target);

    match position_option {
        Some(position) => println!("Element found at position: {}", position),
        None => println!("Element not found in the array"),
    }
}

Code Explanation for Searching for an Element in an Array in Rust

This is a simple program designed to search for a target variable within an array.

First, we declare our array of integers, let array = [10, 20, 30, 40, 50];, and our target element let target = 30;.

let position_option = array.iter().position(|&x| x == target); - Here, we are calling an iterator on the array using .iter() and then using the .position() method. The position() method takes a closure (a short, inline anonymous function), which receives a reference to each element (x) in the array until the closure returns true (meaning it found the target), or until it has looked at every element (in which case it returns None). If the element is found, the method will return the position of the element.

The match position_option line is used to display either a success message with the position of the found element, or an error message if the target isn’t found. The match command in Rust operates similar to the switch statement in other languages. It is an expression that allows branching of logic based on the pattern of the passed variable.

In the match statement, Some(position) corresponds to a successful find. The position of the found element will be printed to the console. None corresponds to the element not being found, and will print an error message. This handling of Some and None is due to the Option type that .position() returns. It is a way in Rust to handle the possibility of absence without having to use null values.

In conclusion, the iter() and position() methods combined with Rust’s powerful match statement provide a simple and effective way to search for an element within an array in Rust.

rust