A Vec<T> stores many values of one type. It can grow with push and be summed with an iterator.

Program

Play the program to push a value and total the vector.

vectors.rs
Replay: real traced execution (multi-file project)
fn main() {
    let mut nums = vec![1, 2, 3];
    nums.push(4);
    let total: i32 = nums.iter().sum();
    println!("{total}");
}
  1. nums ← [1, 2, 3], total ← 10

    1fn main() {2    let mut num→ [1, 2, 3]s = vec![1, 2, 3];3    nums.push(4);4    let tota→ 10l: i32 = nums.iter().sum();5    println!("{total}");6}
    output10

Follow the Vector

  1. nums starts as [1, 2, 3].
  2. nums.push(4) adds 4 to the end.
  3. The vector becomes [1, 2, 3, 4].
  4. The total is 1 + 2 + 3 + 4, which is 10.
  5. The program prints 10. | moment | nums | total | | --- | --- | --- | | start | [1, 2, 3] | - | | after push | [1, 2, 3, 4] | - | | after sum | [1, 2, 3, 4] | 10 |
vec! `vec![1, 2, 3]` builds a vector with initial values.
push `push` appends one value to the end.
iter().sum() `iter().sum()` adds every element.

Exercise: vectors.rs

Reproduce the output 10, then identify which pushed value makes the vector total reach 10.