Rfcs: drain_filter for all collections

Created on 4 Sep 2017  ·  6Comments  ·  Source: rust-lang/rfcs

For all collections, provide a method drain_filter. For some discussion of the method name and signature, see https://github.com/rust-lang/rust/issues/43244, especially this comment.

Status

Implemented, awaiting stabilization

Unimplemented

Description

This method mutably borrows the collection and takes a predicate on the elements of the collection (e.g. values for lists and key-value pairs for maps). It then creates an iterator over the elements of the collection where the predicate returned truthfully and accessing that element in the iterator removes it from the collection. For ordered collections, it should return them in order.

Example usage

let v = vec![1, 2, 3, 4, 5, 6, 7, 8];
let primes = v.drain_filter(|n| n.is_prime()).collect::Vec<_>();
assert!(v == vec![1, 4, 6, 8]);
assert!(primes == vec![2, 3, 5, 7]);

Related ideas

Also of use would be a method that finds and removes the first element matching a predicate, as it would not have to do things like _pre-poop its pants_ in case the Drain Where iterator leaks nor would it have to traverse the entire collection if e.g. the first element checked matches the predicate.

A-collections T-libs

Most helpful comment

I can't say how many times I've needed something like this!

All 6 comments

For Vec see rust-lang/rust#43245 - although I believe all collections can eventually have this.

I can't say how many times I've needed something like this!

VecDeque doesn't have drain_filter either. Shouldn't it be included in the unimplemented list?

@WaffleLapkin VecDeque doesn't have splice either (or something similar that allows extending at the front), but it should!
(SliceDeque supports splice and drain_filter but doesn't work on wasm.)

Added VecDeque to the checklist above.

@mbrubeck What about String::drain_filter? It has retain whose closure gets a char (not &mut char), so we need drain_filter as well for String.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

3442853561 picture 3442853561  ·  3Comments

3442853561 picture 3442853561  ·  3Comments

silversolver1 picture silversolver1  ·  3Comments

mahkoh picture mahkoh  ·  3Comments

3442853561 picture 3442853561  ·  4Comments