Collections
Vectors
A Growable List
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}");
}
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
numsstarts as[1, 2, 3].nums.push(4)adds4to the end.- The vector becomes
[1, 2, 3, 4]. - The total is
1 + 2 + 3 + 4, which is10. - 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.