skip to content

Borrowing vs Consuming Iteration

iter borrows, iter_mut borrows mutably and into_iter consumes, and a for loop picks one through IntoIterator. Interviewers ask why a Vec is unusable after a for loop over it.

on this pageshow

questions

5

In Rust, why is a `Vec<Task>` unusable after `for task in tasks { ... }`, and how do you loop without giving it up?

level: juniorimportance: must knowfreq 82%

answer

  1. what the loop header calls
  2. into_iter takes self
  3. three impls on Vec
  4. borrow in the loop header

basics

~20 s

A Rust for loop calls IntoIterator::into_iter on its expression, and for a Vec<Task> passed by value that takes ownership, so the vector is moved and later use is E0382. Loop over &tasks or &mut tasks to borrow it instead.

solid answer

~40 s

`for task in tasks` is sugar for a loop over `IntoIterator::into_iter(tasks)`. `Vec<T>` implements `IntoIterator` three times: for `Vec<T>` itself (`Item = T`), for `&Vec<T>` (`Item = &T`) and for `&mut Vec<T>` (`Item = &mut T`). Writing `tasks` by value picks the first, which moves the vector into a `std::vec::IntoIter`; each `Task` is moved into the loop body, and any later use of `tasks` is E0382, "borrow of moved value". rustc's own note says the move is the loop's implicit call to `.into_iter()` and suggests `&tasks`. So loop over `&tasks` to read, `&mut tasks` to edit in place, and keep the by-value form for when the body really needs to own each task. The element type does not matter: a `Vec<i32>` is moved the same way, because `Vec` itself is never `Copy`.

code

rust · 14 lines
rust
struct Task {
    title: String,
}

fn main() {
    let tasks = vec![
        Task { title: "write tests".to_string() },
        Task { title: "review PR".to_string() },
    ];
    for task in tasks {
        println!("{}", task.title);
    }
    println!("{} tasks", tasks.len()); // error[E0382]
}

go deeper

for a junior

Recall that the for header calls into_iter on exactly what you wrote, and that writing &tasks or &mut tasks borrows instead of moving.

for a middle

Explain the three IntoIterator impls on Vec, the Item each yields, and why the move happens even when the elements are Copy.

for a senior

Treat the header as a statement of intent in review: flag clone() used to dodge E0382 and consuming loops over data still needed later.

for a principal

Frame borrowing versus consuming as an ownership decision a codebase makes visible at every loop, and keep clones out of hot paths by habit.

## What the loop header actually calls A Rust `for` loop is not a special case for collections. The Reference defines `for PATTERN in iter_expr { body }` as sugar for a loop that first evaluates **`IntoIterator::into_iter(iter_expr)`** once, then repeatedly calls `Iterator::next` on the result until it returns `None`. The key detail is the signature of that first call: `fn into_iter(self) -> Self::IntoIter`. It takes `self` **by value**, so whatever you write after `in` is handed over to `into_iter` exactly as written. There is no auto-referencing here. Method calls such as `tasks.len()` borrow the receiver automatically, because method lookup tries `&tasks` and `&mut tasks` for you. The `for` header is a plain function call on the expression, so `tasks` is passed as a `Vec<Task>`, and passing a non-`Copy` value by value **moves** it. ## The three `IntoIterator` impls on `Vec<T>` The standard library implements `IntoIterator` for a vector three times, and the type of the expression after `in` picks which one runs: | Loop header | Impl chosen | `Item` | What happens to the vector | |---|---|---|---| | `for t in tasks` | `IntoIterator for Vec<T>` | `T` | moved into a `std::vec::IntoIter`, unusable afterwards | | `for t in &tasks` | `IntoIterator for &Vec<T>` | `&T` | shared borrow for the loop's duration | | `for t in &mut tasks` | `IntoIterator for &mut Vec<T>` | `&mut T` | exclusive borrow for the loop's duration | The by-value impl's own doc comment says it "creates a consuming iterator, that is, one that moves each value out of the vector" and that "the vector cannot be used after calling this." Each element is moved into the loop variable in turn; elements the loop never reaches (because of a `break`) are dropped when the `IntoIter` is dropped, and the heap buffer is freed with it. ## Reading the compiler's error For a task list printed and then counted, rustc 1.99 reports **E0382**, "borrow of moved value: `tasks`". The diagnostic is unusually explicit about the cause: - it labels the header with "`tasks` moved due to this implicit call to `.into_iter()`"; - a note says the `for` loop "is desugared into a call to `std::iter::IntoIterator::into_iter`, which takes ownership of the receiver `self`"; - the help line suggests writing `&tasks` instead. The error points at the *later* use, not at the loop, so the fix is easy to miss when the loop sits far above the line that fails. ## Mutating owned items in a consuming loop The by-value form also accepts a mutable binding: `for mut task in tasks { task.title.push('!'); archive.push(task); }` compiles, because each `Task` is now owned by the loop variable and may be changed before it is handed on. That is different from editing the vector in place: the changes live in whatever receives the task, and the vector itself is still gone after the loop. If the goal is to update the list and keep it, the header must be `&mut tasks`. ## Choosing the form on purpose Each header states an intent, and reviewers read it that way: 1. **`for task in &tasks`** when the body only reads — printing a task list, summing estimates, searching. `task` is `&Task`. 2. **`for task in &mut tasks`** when the body edits elements in place, such as setting `task.done = true`. `task` is `&mut Task`; the vector keeps its elements and its length. 3. **`for task in tasks`** when the body needs to **own** each element — pushing it into an archive `Vec`, sending it through a channel, passing it to a function that takes `Task` — and the vector has no later use. Two habits are worth avoiding: - Writing `for task in tasks.clone()` to silence E0382. It compiles, but it deep-copies every `Task` (including each `String` allocation) only to throw the copies away. Borrowing costs nothing. - Assuming the vector survives when its elements are `Copy`. A `Vec<i32>` owns a heap buffer and implements `Drop`, so `Vec` is never `Copy`; `for n in numbers` moves `numbers` regardless of the element type. ## Getting the vector back after a consuming loop Once consumed, the old value is gone; the binding can be used again only after you assign it a new vector, which needs `let mut`. If you discover you need both owned elements and a still-usable vector, the usual options are to borrow and clone only the elements you keep, or to empty the vector with `Vec::drain(..)`, which yields owned elements while leaving the vector itself alive. The consuming form is not a mistake in itself: it is the cheapest way to hand every element to a new owner, because nothing is copied and the buffer is released as soon as the loop ends.

  • Does `for n in numbers` still move a `Vec<i32>`, given that `i32` is `Copy`?
    Yes. The loop moves the vector, not just its elements, and `Vec<i32>` is not `Copy` because it owns a heap buffer and implements `Drop`. `numbers.len()` afterwards is E0382. Write `for n in &numbers` (each `n` is `&i32`), or `for &n in &numbers` to copy each integer out through the pattern.
  • Why is `for task in tasks.clone()` a poor fix for the E0382?
    It compiles, but it allocates a full copy of the vector and of every `Task` inside it, often including heap data such as `String` fields, only to drop the copies when the loop ends. If the body only reads, `&tasks` does the same job for free; clone only the individual elements you actually need to own.
  • When is consuming the vector with `for task in tasks` the right choice?
    When the body needs ownership of each element and the vector has no later use: moving tasks into an archive, sending them to another thread, or passing them to a function that takes `Task`. Nothing is copied, and the buffer is freed when the loop's iterator is dropped.

  • A for loop only reads a Vec, so the Vec stays usable afterwards.
  • The Vec stays usable when its element type is Copy.
  • The loop header borrows automatically, like a method call does.
  • Cloning the vector before the loop is the normal fix.
  • The error after a consuming loop is E0499, a double mutable borrow.
open as a page

For a Rust `Vec<T>`, what does each of `iter()`, `iter_mut()` and `into_iter()` yield, and which `for` loop form matches each one?

level: middleimportance: must knowfreq 74%

basics

~20 s

On 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.

open as a page

In Rust, when you archive every `Task` from a `Vec<Task>` you keep reusing, why call `tasks.drain(..)` instead of `tasks.into_iter()`?

level: middleimportance: should knowfreq 42%

basics

~20 s

Vec::drain(..) takes &mut self and yields each Task by value while leaving the vector alive, empty and with its buffer, ready for refilling. into_iter() takes self, so it consumes the vector and frees its buffer once the iterator is dropped.

open as a page

When rustc desugars a Rust `for pattern in expr` loop, which calls does it make, and what does that let you write after `in`?

level: middleimportance: should knowfreq 48%

basics

~20 s

rustc turns a for loop into one call to IntoIterator::into_iter(expr) followed by a loop that calls Iterator::next and breaks on None. Anything implementing IntoIterator can follow the in keyword: collections, references to them, ranges, and any iterator, including &mut iter.

open as a page

When a Rust function either reads or takes ownership of a batch of `Task`s, when should its parameter be `impl IntoIterator` rather than `&[Task]` or `Vec<Task>`?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Use impl IntoIterator<Item = Task> to consume or Item = &'a Task to read when the body makes one pass: callers may pass a Vec, array, slice, drain or iterator. Use &[Task] for indexing or repeated passes, Vec<Task> for storing.

open as a page