How to implement a trait when an associated type includes a closure?

Viewed 123

I would like to implement IntoIterator using a map over an iterator, like this:

struct MyStruct {
    txt: String,
}

impl IntoIterator for MyStruct {
    type Item = String;
    type IntoIter = std::iter::Map<std::ops::Range<char>, WhatAmISupposedToWriteHere>;

    fn into_iter(self) -> Self::IntoIter {
        ('a'..'z').into_iter().map(move |c| {
            let mut t = self.txt.clone();
            t.push(c);
            t
        })
    }
}

What is the type of my |c| self.txt.clone().push(c) closure that I'd have to write into the IntoIter type?

  • The IDE says the type is [closure@src/example.rs:16:36: 16:64] which isn't very useful.
  • I tried dyn Fn(char) -> String but then the compiler complains that IntoIter doesn't have a size known at compile-time.
  • I also tried just writing _ instead of a specific type, but an _ is not allowed in a type signature - although it looks like the compiler can definitely find out the type on its own, so it would be nice if it would just magically define IntoIter for me.

What is the correct way of using map when implementing IntoIterator?

0 Answers
Related