In Rust, when you archive every `Task` from a `Vec<Task>` you keep reusing, why call `tasks.drain(..)` instead of `tasks.into_iter()`?
answer
- owned items, live vector
- &mut self, not self
- capacity left in place
- dropping Drain early
basics
~20 sVec::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.
solid answer
~40 s`into_iter()` on a `Vec<T>` takes `self`: the vector is moved, its elements come out by value, and the allocation goes away with the `IntoIter`. `Vec::drain(range)` takes `&mut self` and returns a `std::vec::Drain` that also yields owned `T`, but only borrows the vector. With `..` it removes every element; the vector stays usable and keeps its capacity, which is what a buffer refilled each tick or batch wants. The `Drain` holds the mutable borrow while it lives, so pushing to the vector meanwhile is E0499. If the `Drain` is dropped early, for instance by a `break`, it drops the remaining elements of the range, so a full-range drain still leaves the vector empty. A sub-range such as `drain(..n)` shifts the tail down, and a bad range panics.
code
rust · 24 linesstruct Task(&'static str);
impl Drop for Task {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
fn main() {
let mut tasks = vec![Task("a"), Task("b"), Task("c")];
let cap = tasks.capacity();
let mut archive = Vec::new();
archive.extend(tasks.drain(..));
assert!(tasks.is_empty());
assert_eq!(tasks.capacity(), cap); // the buffer stays for refilling
tasks.push(Task("d"));
tasks.push(Task("e"));
for t in tasks.drain(..) {
println!("took {}", t.0);
break; // the Drain is dropped here and drops "e" too
}
println!("len after break = {}", tasks.len());
println!("archived {}", archive.len());
}go deeper
Recall that drain(..) gives owned elements but keeps the vector, while into_iter on an owned Vec uses the vector up.
Explain the signatures: drain borrows with &mut self and returns Drain, into_iter takes self and returns IntoIter, and what each does to the capacity.
Check every exit path of a drain loop: an early break drops the rest of the range, and a forgotten Drain can leak elements.
Pick a buffer-reuse convention for hot paths, draining long-lived buffers and consuming locals, and make it explicit in code review guidance.
## Two ways to get owned elements out Both calls hand you each element **by value**, so either can feed an archive with `archive.push(task)` or `archive.extend(...)`. The difference is what happens to the vector: | | `tasks.into_iter()` | `tasks.drain(..)` | |---|---|---| | Receiver | `self` (moves the vector) | `&mut self` (borrows it) | | Iterator type | `std::vec::IntoIter<T>` | `std::vec::Drain<'_, T>` | | `Item` | `T` | `T` | | Vector afterwards | gone; using it is E0382 | still there, length 0 | | Allocation | freed when the iterator is dropped | kept: capacity unchanged | | Partial range | not possible | `drain(a..b)` removes just that range | When the vector is a long-lived field or a buffer you refill — a pending-task queue on a struct, a batch reused every frame or every request — `into_iter` would require replacing the field and reallocating on the next push. `drain(..)` empties it in place. ## What `Vec::drain` promises The doc comment on `Vec::drain` is short and worth reading closely: - It **removes the subslice indicated by the range** and returns a **double-ended iterator** over the removed elements, so `rev()` works on it. - **"If the iterator is dropped before being fully consumed, it drops the remaining removed elements."** A `break` out of `for t in tasks.drain(..)` therefore does not leave the untouched tasks in the vector; they are dropped, and `tasks.len()` is 0. - **"The returned iterator keeps a mutable borrow on the vector."** While the `Drain` is alive you cannot touch the vector: pushing to it is **E0499**, "cannot borrow `v` as mutable more than once at a time", with a note that the borrow may be used when the `Drain` is dropped. - **It panics** if the range's start is greater than its end, or if a bounded end lies past the vector's length. - Under **Leaking**, the docs warn that if the `Drain` goes out of scope without being dropped (for example via `mem::forget`), the vector may lose and leak elements arbitrarily, including ones outside the range. That is memory-safe but surprising; never forget a `Drain`. On capacity, the doc example notes that a full-range `v.drain(..)` clears the vector "like `clear()` does", and `clear` is documented to have no effect on allocated capacity. Running the code confirms that `capacity()` is unchanged after a full drain. ## Ranges other than `..` `drain` accepts any `RangeBounds<usize>`. `tasks.drain(..10)` takes the first ten tasks and moves the tail down to close the gap, which costs a copy of the remaining elements; `tasks.drain(n..)` takes a suffix with no shifting. When you want to remove only the elements that match a condition rather than a contiguous range, that is a filtering job for other `Vec` methods, not for `drain`. ## Choosing between the alternatives 1. **`for t in tasks`** or `tasks.into_iter()` — the vector is a local you are finished with. Cheapest and clearest. 2. **`tasks.drain(..)`** — the vector must survive, empty, with its allocation, and you want to process each element as it comes out. 3. **`archive.append(&mut tasks)`** — you only need to move all elements into another `Vec<Task>`. `Vec::append` moves all elements of the other vector, leaving it empty, without an element-by-element loop. 4. **`std::mem::take(&mut tasks)`** — you want the whole vector as an owned value (to return it or send it elsewhere); it leaves a fresh empty `Vec` behind, so the original allocation leaves with the value. A similar `drain` exists on other collections (`HashMap::drain`, `VecDeque::drain`, `String::drain`), each with its own signature; the points above are about `Vec::drain`. ## Reading a drain loop in review A useful check is to ask what happens on every exit path. On normal completion, every element has been yielded and moved. On `break` or an early `return`, the `Drain` is dropped and the rest of the range is dropped with it — fine for an archive flush, wrong if the code expected the leftover tasks to stay queued. If they must stay, process them with a borrowing loop first and drain only what you have committed to move. A second review point is how long the `Drain` lives. Writing `let batch = tasks.drain(..);` and passing `batch` around keeps the vector exclusively borrowed until `batch` is dropped, so any later `tasks.push(...)` in the same scope fails with E0499. Draining directly into a consumer, as in `archive.extend(tasks.drain(..))`, ends the borrow at the end of that statement.
- After `for t in tasks.drain(..) { if t.blocked { break; } archive.push(t); }`, are the tasks after the blocked one still in `tasks`?No. Breaking drops the `Drain`, and its documented behaviour is to drop the remaining removed elements, so the blocked task and everything after it are dropped and `tasks` is empty. To keep them, find the cut-off index with a borrowing loop first and call `tasks.drain(..i)`.
- When is `std::mem::take(&mut tasks)` a better fit than `tasks.drain(..)`?When you want the whole `Vec<Task>` as one owned value, for example to return it or send it to another thread, rather than element by element. `take` swaps in a new empty vector, so the original buffer travels with the value and the field starts again with no capacity.
Emptying a reusable shipping crate onto the shelf versus shipping the crate itself: drain(..) takes every item out and leaves the empty crate in place for the next load, while into_iter() sends the crate away with its contents.
- drain(..) moves the vector, so it cannot be used afterwards.
- Breaking out of a drain loop leaves the unvisited elements in the vector.
- drain(..) frees the buffer the same way into_iter does.
- You can push to the vector while its Drain is still alive.
- drain yields references to the removed elements.