Best way to delete unwanted items from collection

Here I have a HashMap, which contains some items worth keeping only for a limited time. Every once in a while, about once every 30 seconds, I need to go through and remove all the expired entries.

struct PendingHandle {
    pub timestamp: u64,             // for discarding old unmatched entries
    pub handshake: RegionHandshake, 
}

...

    pub waiting_for_handle: HashMap<LLUUID, PendingHandle>,       

...

Here's the part that does the deletion.

    let deluuids: Vec::<LLUUID> = self.waiting_for_handle.iter()
        .filter_map(|item| if Pending::ifexpired(now, item.1.timestamp) { Some(item.0.clone()) } else {None}).collect();    // list of items to delete
    deluuids.iter().for_each(|uuid| {let _ = self.waiting_for_handle.remove(uuid); });   // delete all collected

So this builds up a list of items to delete, a vector of LLUUIDs, and then deletes them.
Can't remove elements from a HashMap over which I'm iterating, right? So this has to be a two phase process.

The deletion in the for_each needs "let _" because I have to consume the unwanted result to get the iterator to run.

I can't do this all in one expression because type inference needs the type information on the first "let" to resolve some ambiguity.

This works but seems too clunky.

You can use retain :wink:

something like

self.waiting_for_handle
    .retain(|_k, v| !Pending::ifexpired(now, v.timestamp));
3 Likes

Oh, nice! Thanks. Didn't know collections had that feature.