Rust Guide > Documentation > Iterators > Min

Introduction

The min function in Rust is a method provided by the Iterator trait that allows you to find the minimum element in an iterator. It returns an Option that contains the minimum value if the iterator is not empty, or None if the iterator is empty. This function is useful for determining the smallest element in a collection.

Syntax

The basic syntax of the min function is as follows:

iterator.min()

Here, iterator is any type that implements the Iterator trait. The resulting value is the minimum element of the iterator wrapped in an Option.

Example Usage

Example 1: Finding the Minimum Value in a Vector

fn main() {
    let numbers = vec![3, 1, 4, 1, 5, 9];
    let min_value = numbers.iter().min();
    println!("{:?}", min_value); // Output: Some(1)
}

Example 2: Finding the Minimum Character in a String

fn main() {
    let text = "rustacean";
    let min_char = text.chars().min();
    println!("{:?}", min_char); // Output: Some('a')
}

Example 3: Finding the Minimum of an Empty Iterator

fn main() {
    let empty: Vec<i32> = vec![];
    let min_value = empty.iter().min();
    println!("{:?}", min_value); // Output: None
}

Example 4: Finding the Minimum of Floats

fn main() {
    let numbers = vec![2.5, 3.1, 1.4, 4.8];
    let min_value = numbers.iter().min_by(|a, b| a.partial_cmp(b).unwrap());
    println!("{:?}", min_value); // Output: Some(1.4)
}

Example 5: Finding the Minimum Based on a Key

fn main() {
    let people = vec![
        ("Alice", 30),
        ("Bob", 25),
        ("Charlie", 35),
    ];
    let min_person = people.iter().min_by_key(|&(_, age)| age);
    println!("{:?}", min_person); // Output: Some(("Bob", 25))
}

Considerations

  • The min method returns None for an empty iterator.
  • For floating-point numbers, use min_by with partial_cmp to avoid NaN issues.
  • The min method consumes the iterator, meaning that the original iterator cannot be used after the min operation.

See Also

  • max - Finds the maximum element of an iterator.
  • filter - Creates an iterator that only yields elements that satisfy a predicate.
  • fold - Reduces an iterator to a single value by applying a function.