`IntoIter` type when the `into_iter` is a bunch of `values`, `map`, `flatten` etc. calls?

I'm trying to implement IntoIterator for my type and I'm not sure how to specify the associated type IntoIter.

The into_iter function body looks like this:

self.set.values().map(TraitPreds::iter).flatten()

So the concrete iterator type is a complex type and I don't want to figure it out myself. Normally in a non-trait method I'd use impl Iterator<Item = ...> + '_, but that's not valid when specifying associated types.

I'd normally not care and just implement non-trait into_iter/iters and use them explicitly in the loops, but I have code that iterates the previous version of this type currently and I'm trying to be somewhat backwards compatible to keep the diff small.

Is there a trick to this? Do I have to manually figure out the concrete iterator type here?

on stable, if you don't wnat to box the result, I'm afraid you'll have to figure out the full type name.

On nightly?

on nightly, there's #![feature(impl_trait_in_assoc_type)]:

impl IntoIterator for MyType {
    type Item = i64;
    type IntoIter = impl Iterator<Item = Self::Item>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter().map(|x| 2 * x as i64)
    }
}

playground:

3 Likes

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.