The OP proposal is a bit too magical for me and I am not sure if we should do it (though it’s indeed a cool concept), so I would like to comment a bit on enum based approach.
Personally I don’t like enum impl Trait
syntax and think that it will make function signatures over-cluttered. I would like to suggest an alternative aproach: why not introduce a macro which will construct anonymous enum and will wrap returns? Code could look like this:
fn foo(flag: bool) -> impl Display {
if flag {
enum_impl!(1)
} else {
enum_impl!("foo")
}
}
It will be lowered into:
fn foo(flag: bool) -> Self::AnonEnum {
enum AnonEnum {
B1(u32),
B2(&'static str),
}
impl std::fmt::Display for AnonEnum { .. }
if flag {
AnonEnum::B1(1)
} else {
AnonEnum::B2("foo")
}
}
This approach is quite explicit and does not clutter signatures though enum_impl!
is a bit magical and I am not sure if it will be possible to implement it as not-builtin, but then question is do we need enum_impl!
or should it just work.