Impl in associated type limitation

Hi,

I guess that this code is not compiling since Rust cannot infer which is the real type to put there, but I am wondering which could be the best solution avoiding boxing of the returned iterator.
It would be great if the IntoIter associated type will be as generic as possible (suppose that in the future I will switch from map to filter).

struct MyRange {
    start: i32,
    end: i32,
}

impl<'a> IntoIterator for &'a MyRange {
    type Item = i32;
    type IntoIter = impl Iterator<Item = i32>; // This is not "still" possible
    
    fn into_iter(self) -> Self::IntoIter {
        (self.start..=self.end).map(|i| i * 2)
    }
}

Thank you

RPITIT [1] (return-position impl Trait in trait) is indeed not yet available today.

If you want that much flexibility, the best way is probably to define an custom type with private fields that implements Iterator and

  • just contains the logic in the Iterator implementation directly
  • contains a Box<dyn Iterator<Item=i32>> for now (for ease of implementation)
  • contains a nameable type using function pointers in place of the closure types
    • (but you don't gain a lot over boxing as the function pointers still introduce indirection)

And then sometime in the future, you may be able to replace it with some form of TAIT (trait alias impl Trait), which is what return-position impl Trait uses under the hood. [2]


  1. :frog: ↩︎

  2. And unlike RPIT, your custom type will still be nameable by others. ↩︎

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.