0

I want to map a collection and return a mutable reference like this.

pub type IterMut<'s> = std::slice::Iter<'s, (EntityId, Vec<&'s mut dyn Component>)>;

pub fn iter_mut(&mut self) -> IterMut<'_>
{
    let components: Vec<(EntityId, Vec<&mut dyn Component>)> = self.entity_indexes
        .iter()
        .filter_map(|(entity_id, _)| match self.get_mut(*entity_id) {
            Some(components) => Some((*entity_id, components)),
            None => None,
        })
        .collect();

    components.iter()
}

The signature of the get_mut function is that :

pub fn get_mut(&mut self, entity_id: EntityId) -> Option<Vec<&mut dyn Component>>

I don't really understand why, but the compiler sends me an error

cannot infer an appropriate lifetime for autoref due to conflicting requirements

note: expected `std::slice::Iter<'_, (entity::EntityId, std::vec::Vec<&mut (dyn component::Component + 'static)>)>`
found `std::slice::Iter<'_, (entity::EntityId, std::vec::Vec<&mut (dyn component::Component + 'static)>)>`

I guess it is related to mutability cause the immutable version of this function don't cause any problem.

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • Does this answer your question? [How can I create my own data structure with an iterator that returns mutable references?](https://stackoverflow.com/questions/25730586/how-can-i-create-my-own-data-structure-with-an-iterator-that-returns-mutable-ref) – E_net4 Sep 24 '21 at 16:12
  • The short version is that you will need to build a custom iterator type for your struct. Without a proper [mre], this is as much as we can do here. – E_net4 Sep 24 '21 at 16:14
  • `components.iter()` will yield *references* to `components` but its going to be destroyed when the function returns, perhaps you wanted `components.into_iter()`? – kmdreko Sep 24 '21 at 16:25

0 Answers0