Iterators behind a Ref


I'm trying to iterator on a struct containing a Ref. Thanks to some research I managed to find a working solution. (See the iter() function on the Shop struct).

The following playground show the issue: Rust Playground.

Now, I want to map that iterator and keep it inside some a struct (see the iter_id() function of the Shop struct. I want to iterate using my ref and adding a mapping to each elements. Sadly I struggle a lot with this approach. For instance I can't write the type of IntoIter on the ItemsId implementation because it requires std::iter::Map and I don't know how to write the lambda part of the Map iterator.

Note that I don't want to allocate any vectors.

Thanks for the help.

You can use a function pointer type:

impl<'a, 'b: 'a, T: 'a + ShopItem> IntoIterator for &'b ItemsId<'a, T> {
    type IntoIter = std::iter::Map<Iter<'a, T>, fn(&'a T) -> &'a usize>;
    type Item = &'a usize;

    fn into_iter(self) -> Self::IntoIter {
1 Like

Thanks this worked, I completely forgot I could write it like that.

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.