Mutable iterator over ordered subset of HashMap

Hi folks! I'd like to implement a mutable iterator over some HashMap values, where next() elements and order are determined by a user provided Vec of keys.

Can anybody explain how it would be done, or alternatively why it's just not possible? My naive example doesn't compile:

use std::collections::HashMap;

/// A HashMap where we can iterate mutable over a ordered subset
struct CustomMap(HashMap<char, u32>);

impl CustomMap {
    /// Get a mutable iterator for the given subset
    fn iter_mut(&mut self, subset: Vec<char>) -> IterMut {
        IterMut {
            map: &mut self.0,
            ordered_subset: subset,
            current: 0,
        }
    }
}

struct IterMut<'a> {
    map: &'a mut HashMap<char, u32>,
    ordered_subset: Vec<char>,
    current: usize,
}

impl<'a> Iterator for IterMut<'a> {
    type Item = &'a mut u32;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self.current < self.ordered_subset.len() {
            true => {
                let key = self.ordered_subset[self.current];
                self.current += 1;
                self.map.get_mut(&key)
                //       ^--- compiler error
                // error[E0495]: cannot infer an appropriate lifetime
                // for autoref due to conflicting requirements [...]
            }
            false => None,
        }
    }
}

fn main() {
    let mut abc = CustomMap(HashMap::new());
    abc.0.insert('A', 1);
    abc.0.insert('B', 2);
    abc.0.insert('C', 3);
    let iter = abc.iter_mut(vec!['A', 'B']);
}

This is the same thing as discussed in this recent thread.

2 Likes