Rust Vectors
Store a growable list with Vec and sum it with an iterator.
Rust
fn main() {
let mut scores = vec![82, 91, 76];
scores.push(95);
let total: i32 = scores.iter().sum();
println!("{} {}", scores.len(), total);
}Output
4 344
Explanation
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.
Explore the dry run
Guided walkthroughReady
1
fn main() {2
let mut scores = vec![82, 91, 76];3
scores.push(95);4
let total: i32 = scores.iter().sum();5
println!("{} {}", scores.len(), total);6
}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 |
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.