Iterator usage questions

The problem here is that you're not returning an Iterator<Item = char>, but a FlatMap<stuff>. Of course, the FlatMap struct implements the Iterator trait, but in Rust there is a distinction between the concrete struct and the trait.

Some months ago (a year?) the impl Trait feature was added to the language, and it allows you to write that a function returns an impl Trait, which means “I'm returning some concrete struct/enum that implements this trait, but I won't tell you which!”. This means you don't have to write out the full type of the struct, since the types can get quite unwieldy, and when using closures, you may not even be able to write it out.

However, even if you use impl Trait, there must still be some specific type that you're returning. This means you can't return two different types of iterator in an if {} else {}, and it also means you cannot use it when creating a trait. All types that implement your trait would have to return the same struct/enum, and that's not enforceable when it is as global a thing as a trait; it may even be implemented in a different crate.

I know in this specific case there is only one impl, but that's the deal. You must either:

  1. Write out the full type. (since you have a closure, it needs to be put into an actual function, so you can mention the type)
  2. Create your own struct and implement Iterator for it.
  3. Use Box (which is a bit less efficient).

You may want to read this thread.