There's also been discussion of having a way for the compiler to do this for you in expressions, often called "enum impl trait":
The idea being then that you'd just be able to write something like
fn pick_impl(b: bool) -> impl Trait {
enum if b {
make_trait_0()
} else {
make_trait_1()
}
}
And the compiler would generate an enum automatically that delegated the trait.
(No marker in the signature, because it's no different from if you'd returned Either
internally, but a marker in the expression to not regress the usual case where it's better to get an error for mismatched things -- with that error mentioning enum if
as a way out, probably.)
The other thing you can do today, if you don't need to return it, is something like this:
let temp_0;
let temp_1;
let my_fn: &dyn Trait =
if predicate { temp_0 = make_trait_0(); &temp_0 }
else{ temp_1 = make_trait_1(); &temp_1 };
to type-erase without needing to Box
things.