Skip to content

drain_filter for all collections #2140

Open
@Havvy

Description

@Havvy

For all collections, provide a method drain_filter. For some discussion of the method name and signature, see rust-lang/rust#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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-collectionsProposals about collection APIsT-libs-apiRelevant to the library API team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions