Skip to content

Vec::retain could (should?) give &mut T to the closure, not just &T #25477

Closed
@SimonSapin

Description

@SimonSapin

Vec<T> has this method:

pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool

However, looking at its implementation, I don’t see a reason why the &T part couldn’t be &mut T, allowing in-place mutation of retained items. This would make the method more useful. The only downside that I can see is that the name does not reflect this new capability of the method. I believe this change would be backward-compatible.

This came up at today’s meetup where someone have a Vec<Item> and wanted (but didn’t know how) to iterate the vector, decreasing some quantity inside Item but also removing items from the vector when the quantity reaches zero.

CC @aturon

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions