RS.CLIPPY.DRAIN_COLLECT

Calling `.drain(..).collect()` to move all elements into a new collection

This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: drain_collect. Copyright ©2025 The Rust Team. All rights reserved.

What it does

Checks for calls to .drain() that clear the collection, immediately followed by a call to .collect().

"Collection" in this context refers to any type with a drain method: Vec, VecDeque, BinaryHeap, HashSet,HashMap, String

Why is this bad?

Using mem::take is faster as it avoids the allocation. When using mem::take, the old collection is replaced with an empty one and ownership of the old collection is returned.

Known issues

mem::take(&mut vec) is almost equivalent to vec.drain(..).collect(), except that it also moves the capacity. The user might have explicitly written it this way to keep the capacity on the original Vec.

Example

fn remove_all(v: &mut Vec<i32>) -> Vec<i32> {
    v.drain(..).collect()
}

Use instead:

use std::mem;
fn remove_all(v: &mut Vec<i32>) -> Vec<i32> {
    mem::take(v)
}