Start learning free

LESSON 275 OF 679 · TUPLES, SORTING & BUILT-INS

Min, Max and Sum in Rust

Lesson

TL ; DR:

v.iter().min() and v.iter().max() give the smallest and the largest value of a vector, in an Option.

v.iter().sum() adds all the values up.


let prices = vec![4, 9, 2, 7];

println!("{}", prices.iter().min().unwrap());    // 2

println!("{}", prices.iter().max().unwrap());    // 9

let total: i32 = prices.iter().sum();

println!("{}", total);                           // 22


Full lesson:

In Maximum Number In Array, a loop found the largest value. In Sum of Numbers, a loop added numbers up. These jobs come up all the time. Rust iterators have them built in.

  • v.iter().min() finds the smallest value of the vector v.
  • v.iter().max() finds the largest value.
  • v.iter().sum() adds all the values up.

min() and max() return an Option, as in Option & Some. An empty vector has no smallest value, so they give None there. unwrap() takes the value out.

That value is a reference into the vector. Put * in front to get the plain number, as in *v.iter().min().unwrap().

sum() needs to know its number type, as in Vec & Iterators. Write it on the variable, as in let total: i32.

Watch out for an empty vector. There, unwrap() finds None and the program panics. When the vector may be empty, use unwrap_or(&0) for a fallback. sum() of an empty vector is 0.


Your task

minutes holds how many minutes you practiced coding on each day of a week.

Store the shortest day in shortest and the longest day in longest. Store the week's total in total.

Use the built-ins from this lesson. The code at the bottom prints all three.

Expected output:

shortest = 15
longest = 60
total = 235
STEP 1 OF 3
    Ctrl + Enter to check