Lifetime error when creating mutable iterator

Viewed 103

I had some problems when I tried to create a custom iterator. The non-mutable version worked fine but when copying the same function to create a mutable version, a lifetime error appeared. This is a simplified version of my problem:

struct Test {
    map: HashMap<u32, String>
}

impl Test {
    pub fn iter(&self, start: u32, end: u32) -> impl Iterator<Item = &String> {
        (start..=end).filter_map(move |i| {
            self.map.get(&i)
        })
    }

    pub fn iter_mut(&mut self, start: u32, end: u32) -> impl Iterator<Item = &mut String> {
        (start..=end).filter_map(move |i| {
            self.map.get_mut(&i)
        })
    }
}

The iter function works fine but the iter_mut function doesn't compile with this error:

error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> src/main.rs:21:22
   |
21 |             self.map.get_mut(&i)
   |                      ^^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime `'_` as defined on the body at 20:34...
  --> src/main.rs:20:34
   |
20 |         (start..=end).filter_map(|i| {
   |                                  ^^^
note: ...so that closure can access `self`
  --> src/main.rs:21:13
   |
21 |             self.map.get_mut(&i)
   |             ^^^^^^^^
note: but, the lifetime must be valid for the anonymous lifetime defined on the method body at 19:21...
  --> src/main.rs:19:21
   |
19 |     pub fn iter_mut(&mut self, start: u32, end: u32) -> impl Iterator<Item = &mut String> {
   |                     ^^^^^^^^^
note: ...so that the types are compatible
  --> src/main.rs:19:57
   |
19 |     pub fn iter_mut(&mut self, start: u32, end: u32) -> impl Iterator<Item = &mut String> {
   |                                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: expected `std::option::Option<&mut std::string::String>`
              found `std::option::Option<&mut std::string::String>`
1 Answers

As said Todd, compile error on iter_mut likely occurs due to creation many mutable references to the same HashMap, but I'm not sure about that. You can do something like that:

struct Test {
    map: HashMap<u32, String>
}

impl Test {
    pub fn iter(&self, start: u32, end: u32) -> impl Iterator<Item=&String> {
        self.map
            .iter()
            .filter_map(move |k| {
                if (start..=end).contains(k.0) {
                    Some(k.1)
                } else {
                    None
                }
            })
    }

    pub fn iter_mut(&mut self, start: u32, end: u32) -> impl Iterator<Item=&mut String> {
        self.map
            .iter_mut()
            .filter_map(move |k| {
                if (start..=end).contains(k.0) {
                    Some(k.1)
                } else {
                    None
                }
            })
    }
}

Related