Rust Guide > Documentation > Iterators > Find

Introduction

The find function in Rust is an iterator adapter that searches for the first element in an iterator that satisfies a given predicate. This function is useful when you need to locate a specific element based on a condition.

Syntax


iterator.find(|&element| condition)
The find function takes a closure that returns a boolean value. It returns an Option containing the first element that satisfies the predicate, or None if no such element is found.

Example Usage

Example 1: Finding the First Even Number

fn main() {
    let numbers = vec![1, 3, 5, 7, 8, 9];
    let first_even = numbers.into_iter().find(|&x| x % 2 == 0);
    println!("{:?}", first_even); // Output: Some(8)
}

Example 2: Finding a Specific String

fn main() {
    let words = vec!["apple", "banana", "cherry"];
    let find_banana = words.into_iter().find(|&word| word == "banana");
    println!("{:?}", find_banana); // Output: Some("banana")
}

Example 3: Finding the First Negative Number

fn main() {
    let numbers = vec![10, 20, -30, 40];
    let first_negative = numbers.into_iter().find(|&x| x < 0);
    println!("{:?}", first_negative); // Output: Some(-30)
}

Example 4: Finding the First Empty String

fn main() {
    let strings = vec!["hello", "world", ""];
    let find_empty = strings.into_iter().find(|&s| s.is_empty());
    println!("{:?}", find_empty); // Output: Some("")
}

Example 5: Finding the First True Value in a Boolean Vector

fn main() {
    let bools = vec![false, false, true, false];
    let first_true = bools.into_iter().find(|&b| b);
    println!("{:?}", first_true); // Output: Some(true)
}

Considerations

  • The find function short-circuits, meaning it stops processing as soon as it finds an element that satisfies the predicate.
  • Using find on an empty iterator will always return None.
  • Ensure the closure used in find does not have side effects, as it may not run for all elements.

See Also

  • position - Returns the index of the first element that satisfies a predicate.
  • filter - Creates an iterator that only yields elements that satisfy a predicate.
  • any - Checks if any element of an iterator satisfies a predicate.
  • all - Checks if all elements of an iterator satisfy a predicate.