Rust Guide > Documentation > Iterators > Max

Introduction

The max function in Rust is used to find the maximum value in an iterator. This function is useful when you need to determine the largest element in a collection.

Syntax


iterator.max()
The max function returns an Option containing the maximum element if the iterator is not empty, or None if the iterator is empty.

Example Usage

Example 1: Finding the Maximum in a Vector of Integers

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

Example 2: Finding the Maximum in a Range

fn main() {
    let range = 1..10;
    let max_value = range.max();
    println!("{:?}", max_value); // Output: Some(9)
}

Example 3: Finding the Maximum String in a Vector

fn main() {
    let words = vec!["apple", "banana", "cherry"];
    let max_word = words.iter().max();
    println!("{:?}", max_word); // Output: Some("cherry")
}

Example 4: Finding the Maximum in a Filtered Iterator

fn main() {
    let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    let max_even = numbers.iter().filter(|&&x| x % 2 == 0).max();
    println!("{:?}", max_even); // Output: Some(10)
}

Example 5: Finding the Maximum in an Empty Iterator

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

Considerations

  • The max function requires that the elements in the iterator implement the Ord trait, which means they can be compared.
  • Using max on an empty iterator will return None.
  • The max function consumes the iterator, meaning the iterator cannot be used again after calling max.

See Also

  • min - Finds the minimum value in 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.