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>`?
answer
- the Item type states ownership
- what callers may pass
- one pass only
- when you need len or indexing
basics
~20 sUse 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.
solid answer
~40 sThe `Item` type in the bound says whether the function borrows or consumes. `fn archive_all(tasks: impl IntoIterator<Item = Task>)` accepts a `Vec<Task>`, a `[Task; N]`, `tasks.drain(..)` or any iterator of owned tasks without forcing callers to build a `Vec`; `fn print_all<'a>(tasks: impl IntoIterator<Item = &'a Task>)` accepts `&Vec<Task>`, `&[Task]` or `tasks.iter()`. Passing `&tasks` where owned items are required fails with E0271, "expected `Task`, found `&Task`". Costs: the body gets one forward pass, since `into_iter` consumes the parameter and a second call is E0382; there is no `len()` or indexing, so take `&[Task]` when you need random access or several passes; and the function is generic, so it is compiled once per argument type. Take `Vec<Task>` when you keep the vector as-is, so callers' buffers move in without copying.
code
rust · 27 linesstruct Task {
title: String,
}
fn print_all<'a>(tasks: impl IntoIterator<Item = &'a Task>) {
for task in tasks {
println!("{}", task.title);
}
}
fn archive_all(archive: &mut Vec<Task>, tasks: impl IntoIterator<Item = Task>) {
archive.extend(tasks);
}
fn main() {
let mut tasks = vec![
Task { title: "write tests".to_string() },
Task { title: "review PR".to_string() },
];
print_all(&tasks); // &Vec<Task>
print_all(&tasks[..1]); // &[Task]
let mut archive = Vec::new();
archive_all(&mut archive, tasks.drain(..1)); // vec::Drain
archive_all(&mut archive, [Task { title: "deploy".to_string() }]); // [Task; 1]
archive_all(&mut archive, tasks); // Vec<Task>, moved
print_all(&archive);
}go deeper
Recall that Item = Task means the function takes the tasks and Item = &Task means it only reads them.
Explain which caller types satisfy each bound and why passing a reference where owned items are required is E0271.
Choose between impl IntoIterator, a slice and a Vec from what the body does: passes, indexing, storing, and flag a second into_iter call.
Set the API convention for public functions: flexible bounds where callers vary, slices for random access, owned Vec where the value is stored.
## The bound states the ownership contract A parameter typed **`impl IntoIterator<Item = X>`** means "anything that can be turned into an iterator of `X`". The `Item` type carries the borrowing-vs-consuming decision: - **`impl IntoIterator<Item = Task>`** — the function takes ownership of each task. Callers may pass a `Vec<Task>` (moved), a `[Task; N]`, `tasks.drain(..)` (keeping their vector), `Some(task)`, or any iterator chain yielding `Task`. - **`impl IntoIterator<Item = &'a Task>`** — the function only reads. Callers may pass `&Vec<Task>`, `&[Task]`, `&[Task; N]`, `tasks.iter()`, or a sub-slice such as `&tasks[..1]`, and keep everything they passed. The standard library uses the same shape where it consumes sequences: `Extend::extend` takes `T: IntoIterator<Item = A>`, which is why `archive.extend(tasks.drain(..))` and `archive.extend(tasks)` both work. The trait's own documentation calls `IntoIterator` a common bound because it lets the input collection type change. The compiler enforces the contract. Passing `&tasks` to a function that wants `Item = Task` fails with **E0271**, "type mismatch resolving `<&Vec<Task> as IntoIterator>::Item == Task`", labelled "expected `Task`, found `&Task`": a borrowed collection cannot satisfy a request for owned items. ## What the flexibility costs | Parameter | Caller can pass | Body can do | Cost | |---|---|---|---| | `impl IntoIterator<Item = Task>` | `Vec`, array, `drain`, any owned iterator | one pass, owned items | generic: one copy of the function per argument type | | `impl IntoIterator<Item = &'a Task>` | `&Vec`, `&[T]`, `iter()` | one pass, shared items | generic; lifetime in the signature | | `&[Task]` | `&Vec`, `&[T; N]`, sub-slices | `len()`, indexing, many passes, `split_at` | must already be contiguous in memory | | `Vec<Task>` | an owned `Vec` | store it as-is, mutate, reuse its buffer | callers with other shapes must collect first | Three costs deserve attention in review: 1. **One pass.** `into_iter(self)` consumes the parameter, so calling `tasks.into_iter()` twice in the body is **E0382**. Validation followed by processing, or computing a length first, needs a slice or a collected `Vec`. 2. **No length or random access.** An `IntoIterator` gives no `len()`; `size_hint` is only a hint. If the function needs `tasks[i]`, a count up front, or a binary search, `&[Task]` is the honest type. 3. **Monomorphisation.** `impl Trait` in argument position is a generic parameter, so the function is compiled separately for each distinct argument type. That is usually cheap, but in a large API surface the binary-size and compile-time effect is real; the general trade-off belongs with generics and bounds. ## When `Vec<Task>` is the right parameter If the function **stores** the collection — a struct field, a cache, a message it sends on — taking `Vec<Task>` lets a caller who already owns a vector move it in with no copy and no reallocation. Accepting `impl IntoIterator<Item = Task>` there would force `collect()` inside, rebuilding a vector the caller may already have. A useful rule: take the weakest type that supports what the body does, and no weaker than what it stores. ## The lifetime in a borrowing bound A borrowing bound must name its lifetime. `fn print_all(tasks: impl IntoIterator<Item = &Task>)` is rejected on stable Rust with **E0658**, "anonymous lifetimes in `impl Trait` are unstable", and rustc suggests introducing a named parameter: `fn print_all<'a>(tasks: impl IntoIterator<Item = &'a Task>)`. The `'a` only says the references live at least as long as the call; callers never write it themselves. ## Accepting owned or borrowed with one bound Sometimes a read-only function should accept both `Vec<Task>` and `&Vec<Task>`. A where clause with **`I::Item: std::borrow::Borrow<Task>`** does that: owned `Task` and `&Task` both implement `Borrow<Task>`, and the body calls `.borrow()` on each item. It widens the signature, so reserve it for helpers that really are called both ways. ## A short checklist - Does the body need ownership of each element? `Item = Task`; otherwise `Item = &'a Task` or `&[Task]`. - Does it need more than one pass, a length or indexing? `&[Task]`. - Does it keep the collection? `Vec<Task>`. - Is it a public API whose callers have varied shapes (arrays, drains, iterator chains)? `impl IntoIterator`.
- Why does a body that calls `tasks.into_iter().count()` and then loops over `tasks` fail when `tasks: impl IntoIterator<Item = u32>`?`IntoIterator::into_iter` takes `self`, so the first call moves the parameter and the loop's own `into_iter` call is E0382, "use of moved value". The bound promises only one pass. Take `&[u32]`, or collect into a `Vec` first, when the body needs a count and then a second pass.
- How can one read-only helper accept both `Vec<Task>` and `&Vec<Task>`?Make it generic over `I: IntoIterator` with `I::Item: std::borrow::Borrow<Task>`, and call `.borrow()` on each item. Both `Task` and `&Task` implement `Borrow<Task>`, so either form satisfies the bound; the cost is a wider, more generic signature.
- impl IntoIterator parameters can be iterated as many times as needed.
- An IntoIterator parameter always gives the body a len() method.
- Passing &Vec<Task> satisfies impl IntoIterator<Item = Task>.
- Taking Vec<Task> is always the most flexible choice for callers.
- impl Trait in argument position is dynamic dispatch, like dyn Trait.