Any work around for Improperly reduced borrows?

Limits of Lifetimes - The Rustonomicon (

Depends on the situation. The example given has a simple workaround:

    fn get_default<'m, K, V>(map: &'m mut HashMap<K, V>, key: K) -> &'m mut V
        K: Clone + Eq + Hash,
        V: Default,

Here's the issue.

1 Like

actually what I am doing is:|(k, v)| if xx h.remove(k) else xx)

and it could not be done

I mean it's ugly to write code like:

let need_remove = Vec::new();
for (k,v) in map.iter() {
    if xxx {
for k in need_remove.iter() {

HashMap has no map method. Provide a complete example and perhaps someone can help.

sorry, it should be:

h.into_iter().map(|(k, v)| if xx h.remove(k) else xx)

This example is still logically incorrect, since after calling into_iter h is consumed - there's nothing to remove from.

Or if h is a &mut HashMap, it still won't work, as you can't modify the HashMap while iterating over it. (You can't modify anything while iterating over it.)

Perhaps you want retain here.

        let xx: bool = todo!();
        map.retain(|_k, _v| xx);
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.