Vec Drain Moves A Range Out In Place

Vec::drain removes a range and hands the elements to an owning iterator, shortening the Vec while the collected items become independent owned data.

RustData Integrity

Code

rustsnippet
33 lines
#[derive(Debug)]
struct Job {
    name: &'static str,
    done: bool,
}

fn main() {
    let mut queue = vec![
        Job { name: "pack", done: true },
        Job { name: "sign", done: true },
        Job { name: "ship", done: false },
        Job { name: "bill", done: false },
    ];

    // drain(..2) is an owning iterator: drained elements move out, the Vec shrinks
    let done: Vec<Job> = queue.drain(..2).collect();
    for job in &done {
        println!("archived: {} done={}", job.name, job.done);
    }
    println!("queue now holds {} jobs", queue.len());

    // Ranges can start mid-way: drain(1..) takes the tail, keeps the head
    let tail: Vec<Job> = queue.drain(1..).collect();
    println!("kept: {:?}", queue);
    for job in &tail {
        println!("split off: {}", job.name);
    }

    // After draining the Vec stays reusable, capacity intact
    queue.drain(..);
    queue.push(Job { name: "next", done: false });
    println!("reused: {:?}", queue);
}

Inside the snippet

main owns the demonstration: queue.drain(..2) archives the finished jobs, queue.drain(1..) splits off the tail, and a final queue.drain(..) empties the Vec before "next" is pushed back in.

Repetition is confined to for job in &done — the rest of the file is straight-line.

Putting it to use

The prints track the drains step by step — archived: for every moved-out Job, queue now holds for the shrinking len(), kept: for the survivors, reused: for the emptied-but-still-usable Vec — so the ownership hand-off is visible one line at a time.

Core lines

let done: Vec<Job> = queue.drain(..2).collect();
let tail: Vec<Job> = queue.drain(1..).collect();

Interactive Tools for This Topic

FAQ

What does Vec Drain Moves A Range Out In Place print when run?
The script runs standalone; its 5 labeled outputs include `archived:`, `queue now holds`, `kept:`.