std-method
Vec::drain
Remove a range and return an iterator yielding its owned elements. Dropping the drain normally removes the remaining items in that range too. The vector is mutably borrowed while the drain is in use. Invalid ranges panic. Expected stdout (not executed): ["A", "B"] ["C", "D"] Common mistake: Trying to use the original vector while the Drain iterator is still needed.
Formal Syntax & Structure
rust syntaxrust
pub fn drain<R>(&mut self, range: R) -> Drain<'_, T> where R: RangeBounds<usize>Working Example
Example Snippetrust
fn main() { let mut pending = vec!["A", "B", "C", "D"]; let completed: Vec<_> = pending.drain(0..2).collect(); println!("{completed:?} {pending:?}");}