Rust Reference ยท Collections
Rust Vec retain, dedup and drain
Reference for Vec::retain, retain_mut, dedup, dedup_by_key and drain in Rust: filtering in place, removing duplicates, draining ranges, with examples.
Three methods remove many elements at once without building a second vector. retain keeps only the elements for which a closure returns true. dedup removes consecutive duplicates. drain(range) removes a range and hands the removed elements back as an iterator.
All three work in a single O(n) pass, which beats calling remove in a loop (O(nยฒ)).
let mut v = vec![1, 2, 3, 4, 5, 6]; v.retain(|n| n % 2 == 0); // [2, 4, 6]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> Vec<T> { pub fn retain<F: FnMut(&T) -> bool>(&mut self, f: F); pub fn retain_mut<F: FnMut(&mut T) -> bool>(&mut self, f: F); pub fn dedup(&mut self) where T: PartialEq; pub fn dedup_by_key<K: PartialEq, F: FnMut(&mut T) -> K>(&mut self, key: F); pub fn dedup_by<F: FnMut(&mut T, &mut T) -> bool>(&mut self, same_bucket: F); pub fn drain<R: RangeBounds<usize>>(&mut self, range: R) -> Drain<'_, T>; }
| Name | Description |
|---|---|
f |
For retain, a predicate called once per element in order; true keeps the element. |
key |
For dedup_by_key, derives a comparison key from each element. |
same_bucket |
For dedup_by, receives the current element first and the previous kept element second, and returns true to drop the current one. |
range |
Any range of positions: a..b, a..=b, ..b, a.. or ... |
Returns: retain and dedup return nothing. drain returns a Drain iterator that yields the removed elements.
Panics: drain panics when the start is greater than the end or the end is greater than len.
Usage notes
retainvisits elements in order, so a closure with side effects sees them front to back. Elements it rejects are dropped.dedupneeds adjacent equal items. Sort first (or use aHashSet) when duplicates are scattered. Plaindedupkeeps the first of each run.- Dropping a
Drainstill removes the range. If you leak it withmem::forget, the vector may lose more elements than expected, so do not. - The vector is borrowed mutably while a
Drainlives, so you cannot read the vector until the drain is dropped or fully consumed. drain(..)versusclear():drain(..)gives you the elements;clear()just drops them. Both keep the capacity.extract_if(taking out matching elements as an iterator) was stabilized forVecin Rust 1.87 with a range argument. The manualwhileloop above works on any version.- Prefer
retainoverfilter().collect()when the result replaces the original: it avoids a new allocation. - Drain a prefix cheaply with
drain(..n); it shifts the remaining items once, not n times.