Looping a vector
- Rust course
- Beginner
- Lesson 97/115
- 4 min
Iterate vector elements with for.
Loops and vectors
The three ways of looping over a vector mean three different kinds of ownership:
let mut v = vec![1, 2, 3];
for x in &v { println!("{x}"); } // &i32: reads
for x in &mut v { *x *= 2; } // &mut i32: modifies
for x in v { println!("{x}"); } // i32: consumes, v is goneIf you also need the position, use enumerate: for (i, x) in v.iter().enumerate().
Iterator methods
Instead of loops, iterator methods are often clearer:
let notlar = vec![70, 85, 90, 45];
let toplam: i32 = notlar.iter().sum();
let gecen: Vec<&i32> = notlar.iter().filter(|&&n| n >= 50).collect();
let artirilmis: Vec<i32> = notlar.iter().map(|n| n + 5).collect();
println!("{toplam} {:?} {:?}", gecen, artirilmis);
// 290 [70, 85, 90] [75, 90, 95, 50]Practice Raise and list
For let mut fiyat = vec![100, 250, 40];, add a tenth of each price to itself with for f in &mut fiyat. Then print each line as 1: 110 with enumerate (positions start at 1).
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let mut fiyat = vec![100, 250, 40];
for f in &mut fiyat {
*f += *f / 10;
}
for (i, f) in fiyat.iter().enumerate() {
println!("{}: {}", i + 1, f);
}
}Expected output
1: 110 2: 275 3: 44
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why does <code>for x in &v</code> fail when calling <code>v.push(..)</code> inside the loop?
- push is forbidden in loops
- x has the wrong type
- It doesn't fail
- v can't be changed while the loop borrows it Correct answer
Explanation: A growing vector could move to new memory and invalidate the loop's references; the borrow checker prevents this.
2 Loop with position
for (i, x) in v.iter().____() {
println!("{i}: {x}");
}
for (i, x) in v.iter().enumerate() {
println!("{i}: {x}");
}
Explanation: enumerate gives each element as an (index, element) pair.
3 Loop and type of x
| Term | Meaning |
|---|---|
for x in &v |
&i32 |
for x in &mut v |
&mut i32 |
for x in v |
i32 (consumes) |
for (i, x) in v.iter().enumerate() |
(usize, &i32) |