w3resource

Rust Function: Find maximum value

Rust Result and Option types: Exercise-2 with Solution

Write a Rust function that takes a vector of integers and returns the maximum value, return None if the vector is empty.

Sample Solution:

Rust Code:

fn find_max(numbers: Vec<i32>) -> Option<i32> {
    if numbers.is_empty() {
        None
    } else {
        Some(*numbers.iter().max().unwrap())
    }
}

fn main() {
    let numbers1 = vec![10, 5, 20, 15];
    let numbers2: Vec<i32> = vec![];

    match find_max(numbers1) {
        Some(max) => println!("Maximum value: {}", max),
        None => println!("The vector is empty!"),
    }

    match find_max(numbers2) {
        Some(max) => println!("Maximum value: {}", max),
        None => println!("The vector is empty!"),
    }
}

Output:

Maximum value: 20
The vector is empty!

Explanation:

Here's a brief explanation of the above Rust code:

  • The 'find_max' function takes a vector of integers 'numbers'.
  • If the vector is empty, it returns 'None'.
  • If the vector is not empty, it uses the 'max()' method to find the maximum value and returns it as 'Some(max)'.
  • In the 'main' function, we test the 'find_max' function with two vectors, one containing elements and the other empty, and print the result accordingly.

Rust Code Editor:

Previous: Rust Function: Parse string to integer.
Next: Rust Program: Adding two numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust/error_handling/rust-result-and-option-types-exercise-2.php