Of all the recipes in this chapter, this one is probably the most stable, as it is being considered for immediate stabilization. The discussion can be found at https://github.com/rust-lang/rust/issues/34511.
While you can use abstract return types for some forms of dependency inversion, you cannot use them for traditional Java-style factories that return different objects depending on a parameter. This is because abstract return types only hide the specific struct returned on the outside of the function, but still internally rely on a specific return value. Because of this, the following code will not compile:
trait Animal {
fn do_sound(&self);
}
struct Dog;
impl Animal for Dog {
fn do_sound(&self) {
println!("Woof");
}
}
struct Cat;
impl Animal for Cat {
fn do_sound(&self) {
println!("Meow");
}
}
enum AnimalType {
Dog,
Cat,
}
fn create_animal(animal_type: AnimalType) -> impl Animal {
match animal_type...