How to name an associated type on a type with a lifetime bound?

Viewed 20

I am trying to implement IntoIterator for a type which needs to yield an immutable reference of it's inner type like so:

impl<T> IntoIterator for Ref<T>
where
    for<'a> &'a T: IntoIterator,
{
    type Item = T::Item;
    type IntoIter = T::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        todo!()
    }
}

However, the above does not type-check because I declared that &'a T: IntoIterator not T: IntoIterator, and therefore T::Item won't work...how can I name this associated type?

1 Answers

Right after I typed this question, a solution that works came to me, I can just use generics to name the inner types like so:

impl<T, Item, IntoIter> IntoIterator for Ref<T>
where
    for<'a> &'a T: IntoIterator<Item = Item, IntoIter = IntoIter>,
    IntoIter: Iterator<Item = Item>,
{
    type Item = Item;
    type IntoIter = IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        todo!()
    }
}

Hopefully this helps anyone else who may run into this seemingly nefarious situation with associated types. :)

Related