For a Rust `Vec<T>`, what does each of `iter()`, `iter_mut()` and `into_iter()` yield, and which `for` loop form matches each one?
answer
- shared, exclusive, owned
- slice iterators via Deref
- into_iter consumes its receiver
- arrays changed with an edition
basics
~20 sOn a Rust Vec<T>, iter() yields &T, iter_mut() yields &mut T and into_iter() yields owned T while consuming the vector. They match for x in &v, for x in &mut v and for x in v.
solid answer
~40 s`iter()` and `iter_mut()` are slice methods reached through `Vec`'s `Deref` to `[T]`: they return `std::slice::Iter<'_, T>` with `Item = &T` and `std::slice::IterMut<'_, T>` with `Item = &mut T`, borrowing the vector. `into_iter()` is `IntoIterator::into_iter(self)`; on a `Vec<T>` it returns `std::vec::IntoIter<T>` with `Item = T` and moves the vector. The `for` forms call the matching impl: `&v` is the `&Vec<T>` impl (same iterator as `v.iter()`), `&mut v` the `&mut Vec<T>` impl, and `v` the by-value impl. Writing through an `&T` is E0594, with rustc suggesting `&mut`. Two traps: `into_iter()` consumes whatever its receiver is, so on a `&Vec<T>` it yields `&T`; and arrays gained by-value `IntoIterator` in Rust 1.53, with `array.into_iter()` yielding `T` only from the 2021 edition on.
code
rust · 26 lines#[derive(Debug)]
struct Task {
title: String,
done: bool,
}
fn main() {
let mut tasks = vec![
Task { title: "write tests".to_string(), done: false },
Task { title: "review PR".to_string(), done: false },
];
for task in &tasks {
let t: &Task = task; // same as tasks.iter()
println!("[{}] {}", if t.done { "x" } else { " " }, t.title);
}
for task in &mut tasks {
let t: &mut Task = task; // same as tasks.iter_mut()
t.done = true;
}
let mut archive: Vec<Task> = Vec::new();
for task in tasks {
let t: Task = task; // same as tasks.into_iter(); tasks is moved
archive.push(t);
}
println!("{archive:?}");
}go deeper
Recall the three item types: iter gives shared references, iter_mut gives exclusive references, into_iter on an owned Vec gives the values and moves the vector.
Explain that iter and iter_mut come from the slice through Deref, while into_iter is the IntoIterator trait and depends on the receiver's type.
Spot into_iter on a reference that still yields references, and know the array and boxed-slice method-call differences across editions when reading older code.
Decide whether a team spells loops as &v or v.iter() and enforce it with a lint, so the access mode stays obvious in review.
## Three access modes, three item types Rust separates **reading**, **editing in place** and **taking ownership**, and a `Vec<T>` offers one iterator for each: | Call | Iterator type | `Item` | Effect on the vector | Matching `for` form | |---|---|---|---|---| | `v.iter()` | `std::slice::Iter<'_, T>` | `&T` | shared borrow | `for x in &v` | | `v.iter_mut()` | `std::slice::IterMut<'_, T>` | `&mut T` | exclusive borrow | `for x in &mut v` | | `v.into_iter()` | `std::vec::IntoIter<T>` | `T` | moved, unusable after | `for x in v` | `iter` and `iter_mut` are not defined on `Vec` at all: they are methods of the slice type `[T]`, reached because `Vec<T>` dereferences to `[T]`. That is why `iter()` works the same on a `Vec`, a `Box<[T]>`, an array or a `&[T]`, and `iter_mut()` on any of them you can borrow mutably. `into_iter` is different: it is the single method of the **`IntoIterator`** trait, `fn into_iter(self) -> Self::IntoIter`, and which impl runs depends on the type of the receiver. ## How the `for` forms line up A `for` loop calls `IntoIterator::into_iter` on its expression, and `Vec<T>` implements the trait for three types: - **`Vec<T>`** — `Item = T`, iterator `std::vec::IntoIter<T>`; - **`&'a Vec<T>`** — `Item = &'a T`, and its `into_iter` simply returns `self.iter()`; - **`&'a mut Vec<T>`** — `Item = &'a mut T`, returning `self.iter_mut()`. So `for x in &v` and `for x in v.iter()` produce exactly the same iterator. Clippy's pedantic `explicit_iter_loop` lint even prefers the `&v` spelling; which one a team writes is style, not behaviour. The item type decides what the body may do. Assigning to a field through `&T` fails with **E0594**, "cannot assign to `task.done`, which is behind a `&` reference", and rustc labels the header "this iterator yields `&` references" and suggests `&mut tasks`. Moving out of an `&T` (for example pushing `*task` into another `Vec`) fails because a borrow cannot give away ownership; that is when the by-value form, or a deliberate `clone()`, is needed. ## `into_iter` does not always consume the collection A common belief is that `into_iter()` means "owned items". It means "consume the receiver", and the receiver may already be a reference: 1. `v.into_iter()` with `v: Vec<T>` yields `T` and moves `v`. 2. `r.into_iter()` with `r: &Vec<T>` consumes only the reference and yields `&T`; the vector is untouched. 3. `(&mut v).into_iter()` yields `&mut T`, exactly like `v.iter_mut()`. Inside a function that takes `tasks: &Vec<Task>`, `tasks.into_iter()` therefore hands out `&Task`. Read the receiver's type, not the method name, to know what you get. ## Arrays and boxed slices: where the edition matters Until Rust 1.53 only `&[T; N]` and `&mut [T; N]` implemented `IntoIterator`. **Rust 1.53** added `IntoIterator for [T; N]` by value in every edition, so `for s in names` with `names: [String; 3]` yields `String` everywhere. The method-call form is the exception: on the 2015 and 2018 editions the compiler hides that impl from `.into_iter()` calls, so `names.into_iter()` still resolves to the slice impl and yields `&String` (the `array_into_iter` lint warns there); from the **2021 edition** on it yields `String`. The library repeated the pattern for `Box<[T]>`: by-value `IntoIterator` arrived in **1.80**, and `boxed.into_iter()` yields `T` from the **2024 edition**. The edition change itself is a story of its own; for this question, on the 2024 edition every `.into_iter()` on an owned array or boxed slice yields owned items. Note that an array of `Copy` items is itself `Copy`, so `for id in ids` with `ids: [u32; 3]` copies the array and leaves `ids` usable, unlike a `Vec<u32>`. ## Picking one in practice - Reading every element: `for t in &tasks` or `tasks.iter()` when you go on to call iterator methods. - Editing elements in place: `for t in &mut tasks` or `tasks.iter_mut()`. - Handing each element to a new owner and discarding the vector: `for t in tasks` or `tasks.into_iter()`. - Taking owned elements but keeping the vector: not `into_iter` at all, but `Vec::drain(..)`. When a loop's item type is in doubt, a type annotation on a binding in the body (`let t: &mut Task = task;`) turns the question into a compile-time check: rustc reports E0308 at once if the header picked a different impl than you thought. It costs nothing at run time and is a quick way to settle an argument in review.
- Inside `fn summarize(tasks: &Vec<Task>)`, what does `tasks.into_iter()` yield?`&Task`. The receiver is a `&Vec<Task>`, so the `&Vec<T>` impl of `IntoIterator` runs; it consumes only the reference and returns the same `slice::Iter` that `tasks.iter()` would. `into_iter` consumes its receiver, whatever type that is; it does not promise owned items.
- On the 2024 edition, does `for s in names` move a `names: [String; 2]`, and is `names` usable afterwards?Yes, it moves it. The by-value `IntoIterator for [T; N]`, stable since Rust 1.53, yields each `String`, and `[String; 2]` is not `Copy`, so later use is E0382. With `[u32; 3]` the array is `Copy`, so the loop works on a copy and the original stays usable.
- into_iter() always yields owned items, whatever the receiver is.
- for x in &v and v.iter() produce different iterators.
- iter() and iter_mut() are methods defined on Vec itself.
- array.into_iter() yields references on the 2024 edition.
- Writing a field through the items of a loop over &tasks only needs a mut binding.
Assumes Rust 1.99 on the 2024 edition; arrays gained by-value IntoIterator in 1.53, and array.into_iter() yields owned items from the 2021 edition.