Sub topic 10
Iterating over arrays by reference and by value
This chapter assumes you can write a for loop, know the difference between &T and &mut T, and understand moves and the Copy trait at a basic level. It also assumes you are compiling with Rust 2021 or later. You will learn the three ways to loop over an array, what item type each one produces, and which errors to expect when you pick the wrong one.
The three forms of iteration
An array [T; N] can be iterated in three ways. Each one changes what the loop variable is.
| Loop header | Method equivalent | Item type | Array afterwards |
|---|---|---|---|
| `for x in &arr` | `arr.iter()` | `&T` | Still usable |
| `for x in &mut arr` | `arr.iter_mut()` | `&mut T` | Usable after the loop ends |
| `for x in arr` | `arr.into_iter()` | `T` | Moved, unless `T` is `Copy` |
A for loop calls IntoIterator::into_iter on whatever expression follows in. The arrays [T; N], &[T; N], and &mut [T; N] each implement IntoIterator, so each of them works in a for loop. The item type differs because the three implementations differ.
Iterating by reference
Borrowing is the default choice. The loop variable is a reference, so the array stays intact.
fn main() {
let mut scores = [70, 85, 90];
for s in &scores {
println!("read {s}");
}
for s in &mut scores {
*s += 5;
}
println!("{:?}", scores);
for (i, s) in scores.iter().enumerate() {
println!("{i}: {s}");
}
let total: i32 = scores.iter().sum();
let best = scores.iter().copied().max();
println!("total={total} best={best:?}");
}The code shows these points:
println!("{s}")works on&i32because formatting follows references. Arithmetic on the value is where the reference type shows up.- In the
&mutloop you must dereference with*sto assign. Without the*,s += 5fails to compile, because&mut i32does not implementAddAssign<i32>. enumerate()pairs each item with its index. The pattern(i, s)destructures the tuple thatenumerateyields. This is the tuple destructuring from earlier in the chapter series, applied inside a loop header.copied()turns an iterator of&Tinto an iterator ofTwhenT: Copy. Usecloned()whenTis onlyClone.
The &mut loop holds a mutable borrow of the whole array for its duration. You cannot read scores inside that loop body, so write *s += scores[0] and the borrow checker rejects it.
Iterating by value
Writing for p in arr hands you each element as an owned T. This became possible when arrays gained a by-value IntoIterator implementation in Rust 1.53.
fn main() {
let primes: [u32; 4] = [2, 3, 5, 7];
let mut sum = 0;
for p in primes {
sum += p;
}
println!("sum={sum}, still have {:?}", primes);
let names = [String::from("Ada"), String::from("Grace")];
let shouting: Vec<String> = names.into_iter().map(|n| n.to_uppercase()).collect();
println!("{:?}", shouting);
}For primes, u32 is Copy. Since the whole array is Copy too, the loop copies it and primes remains usable on the next line. For names, String is not Copy, so names.into_iter() moves the array into the iterator. Each String is moved out in turn. After that line, any use of names is a "borrow of moved value" error.
Use by-value iteration when you want to take ownership of the elements. Typical cases are moving Strings into another collection, passing each element to a function that consumes it, or avoiding reference syntax for small Copy types.
Gotcha: `into_iter()` and editions
In Rust 2015 and 2018, the method call array.into_iter() still resolved to the by-reference version and yielded &T. The compiler special-cased this to avoid breaking old code. The for x in array syntax was not affected and yields values in every edition. Rust 2021 removed the special case, so array.into_iter() yields T.
Common errors and how to read them
- Use after move. You loop with
for n in namesover an array ofStrings and then printnames. Fix it by looping over&names, or by cloning the array first if you need both. - Mismatched item types.
for s in &scores { total += s; }can work, sincei32: AddAssign<&i32>. Butif s == 90fails, because&i32does not compare withi32. Write*s == 90, orfor &s in &scoresto destructure the reference in the pattern. - Forgetting to dereference in
&mutloops. Assign through*s. - Mutating while iterating. Reading the array inside a
&mutloop, or writing it inside a&loop, is a borrow conflict. Useiter_mut().enumerate()and index only through the loop variable. If you need to compare against neighbours, use indices withfor i in 0..arr.len(), or iterate over a slice method such aswindows. - Unused results from iterator adapters.
arr.iter().map(...)does nothing until you consume it withcollect,sum, aforloop, or similar. The compiler warns about unused adapters.
Patterns in the loop header
The loop variable is a pattern, so you can destructure items directly. This works well with arrays of tuples.
fn main() {
let readings: [(&str, f64); 3] = [("north", 12.5), ("south", 15.0), ("east", 9.75)];
for &(site, value) in &readings {
println!("{site}: {value}");
}
for (site, value) in readings {
println!("{site} -> {:.1}", value * 2.0);
}
let weights = [1, 2, 3];
let scaled = [10, 20, 30];
for (w, s) in weights.iter().zip(scaled.iter()) {
println!("{}", w * s);
}
}In the first loop, the items are &(&str, f64). The pattern &(site, value) removes the outer reference. That works here because both fields are Copy. A tuple with a String field would fail to destructure this way, since the pattern would try to move out of a borrow. In that case use for (site, value) in &readings, which binds site and value as references through default binding modes.
Iterating in other orders
Iterator adapters work the same on arrays as on any other iterator:
arr.iter().rev()walks backwards.arr.iter().skip(1).step_by(2)visits every second element after the first.arr.chunks(2)andarr.windows(2)come from slices. An array coerces to a slice automatically on method calls, so these are available directly.
The array length is known at compile time, and the iterator over it is a small struct. Loops over arrays typically compile to code as tight as hand-written indexing, and bounds checks are often removed by the optimizer.
Exercise
Given let words = [String::from("a"), String::from("bb"), String::from("ccc")];, write a loop that prints each word's length and still lets you use words afterwards. Then say what changes if you write for w in words instead.
Show answer
Use for w in &words { println!("{}", w.len()); } (or words.iter()). Here w is &String, and words is only borrowed, so it remains usable. With for w in words, each String is moved out of the array into w, so words is moved and any later use of it is a compile error ("borrow of moved value").
Exercise
What is the type of x in each loop, assuming let mut a = [1u8, 2, 3]; and edition 2021? (a) for x in &a (b) for x in &mut a (c) for x in a (d) for x in a.iter().copied()
Show answer
(a) &u8. (b) &mut u8. (c) u8, and a is still usable afterwards because [u8; 3] is Copy. (d) u8.