Between returning impl Iterator<...>
, Box<dyn Iterator<...>>
, and writing my own structs that implement Iterator
, I've gotten myself confused. After quite some time trying, I'm unable to write something which on the surface should be obviously possible, namely:
How does one yield an Iterator of
T
that gets thoseT
from potentially branching sources?
Here's a fabricated example:
enum Foo {
A { a: Vec<u32> },
B { a: Vec<u32>, b: Vec<u32> },
}
impl Foo {
fn numbers(&self) -> impl Iterator<Item = &u32> {
match self {
Foo::A { a } => a.iter(),
Foo::B { a, b } => a.iter().chain(b),
}
}
}
This doesn't compile, because the match
branches are technically returning different types, due to how Rust implements iterators as distinct structs. Through what incantation can I get this (or something like it) to compile? Note:
- Don't fuss too much about the
Vec
s, the original sources could be anyIntoIterator
. - The enum-struct fields could be distinct structs (and are in my real code).
-
Box<dyn ...
doesn't immediately work here due to the lifetime onself
. - Manually fusing the
Vec
s or doing an additionalcollect
beforehand are not possible for me.
Am I missing something obvious? Please and thanks.