I was thinking about this, or something like this, in light of impl Trait.
Consider:
fn one() -> impl Iterator<Item=u8> {
std::iter::once(123)
}
This of course works fine. But now consider:
fn one_or_two(two: bool) -> impl Iterator<Item=u8> {
let one = std::iter::once(123);
if two {
one.chain(std::iter::once(234))
} else {
one
} // error[E0308]: if and else have incompatible types
}
Now I can of course solve this by using boxed trait objects. But this kind of defeats one of the purposes of impl Trait, which is reducing heap allocation. The return type of one_or_two is trivially defined as an enum. In fact, a lot of functions that return a boxed trait object could return an enum that implements that same trait instead.
- For which traits is it possible to programmatically generate such enums and trait impls, given a list of types? (All?)
- Can we make this more automated by using a macro/compiler integration?
If you want to support multiple levels of impl Trait return values, it seems impossible to do without compiler magic.