Sub topic 10
Iterating over arrays by reference and by value
This chapter assumes you know basic Rust syntax, can run programs with cargo, and understand & references and borrowing. It covers the three ways to loop over an array and the errors that come from choosing the wrong one.
Three ways to loop
An array can be iterated in three forms. Each one produces a different item type.
| Loop form | Item type for `[T; N]` | Array afterward |
|---|---|---|
| `for x in &arr` | `&T` | Still usable |
| `for x in &mut arr` | `&mut T` | Still usable, elements may have changed |
| `for x in arr` | `T` | Usable only if `T` is `Copy` |
Since Rust 2021, for x in arr moves each element out of the array. Before that edition, arr.into_iter() quietly iterated by reference, which surprised many people. In current code, the array itself is the thing being consumed.
By reference
Use a shared reference when you only need to read the elements.
fn main() {
let names = [String::from("Ada"), String::from("Grace"), String::from("Linus")];
for name in &names {
println!("{} has {} letters", name, name.len());
}
println!("still have {} names", names.len());
}Here name is a &String. The array is only borrowed, so it can be used after the loop.
To change elements in place, borrow mutably:
fn main() {
let mut scores = [10, 20, 30];
for score in &mut scores {
*score += 5;
}
println!("{:?}", scores);
}The item is &mut i32, so you dereference with * to assign.
By value
Looping over the array directly gives you owned elements.
fn main() {
let names = [String::from("Ada"), String::from("Grace")];
for name in names {
let owned: String = name;
println!("took {owned}");
}
// println!("{:?}", names); // error: borrow of moved value: `names`
}If the element type is Copy, such as i32, the array is copied into the loop and stays usable. With String, the array is moved, and using it afterward is a compile error.
Getting indexes
Use enumerate to get a position with each item. It works with any of the three forms.
fn main() {
let letters = ['a', 'b', 'c'];
for (i, ch) in letters.iter().enumerate() {
println!("{i}: {ch}");
}
}The pattern (i, ch) destructures the tuple that enumerate yields. Prefer this to looping over 0..letters.len() and indexing, because it avoids bounds checks and off-by-one mistakes.
Common errors
- Writing
*xwhen looping by value. The item is not a reference, so the compiler reports that the type cannot be dereferenced. - Forgetting
*in a&mutloop.score += 5fails because you cannot add an integer to&mut i32that way. - Reusing a non-
Copyarray afterfor x in arr. Loop over&arrinstead.
Exercise
You have let words = [String::from("a"), String::from("b")];. You write for w in words { println!("{w}"); } and then println!("{}", words.len());. Why does this fail to compile, and what is the smallest change that fixes it?
Show answer
The by-value loop moves each String out of words, so the array is moved and cannot be used afterward. Change the loop to for w in &words, which borrows the array. Then w is a &String and words.len() still works.