Rust Vectors
Store a growable list with Vec and sum it with an iterator.
On this page
Rust variables.
- Store a growable list with Vec and sum it with an iterator.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
Vec<T> is a growable array stored on the heap. The vec! macro builds one from literal values, push adds an item at the end, and len reports the number of items. The vector must be declared mut to be changed.
scores.iter() yields references to each element and sum adds them. The type annotation i32 on total tells Rust what type to add up to, since sum can produce several numeric types.
Code example
fn main() {
let mut scores = vec![82, 91, 76];
scores.push(95);
let total: i32 = scores.iter().sum();
println!("{} {}", scores.len(), total);
}4 344
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
fn main() { let mut scores = vec![82, 91, 76]; scores.push(95); let total: i32 = scores.iter().sum(); println!("{} {}", scores.len(), total);}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| A mutable vector of three integers. | scores = [82, 91, 76] | — | |
| Append a fourth value. | scores = [82, 91, 76, 95] | — | |
| Add all four values. | total = 344 | — | |
| Print the length and the sum. | total = 344 | 4 344 |
Behind the scenes
How Rust processes this code
Rust checks types and ownership at compile time, then builds a native executable.
Cost and common mistakes
push is amortized O(1); sum is O(n) time and O(1) space.
- Indexing a Vec out of range, such as scores[10], panics at runtime; get(10) returns an Option instead.
- You cannot push while holding a reference into the vector, because a push may move its storage.
Try it yourself
Print the average as a float.
Reveal answer and reasoning
Convert both values: total as f64 / scores.len() as f64 gives 86.