I'm trying to write a function in rust that builds different types of objects (all implementations of a same trait) but I'm running into troubles, not understanding if I'm trying to do something illegal or just not grasping correct syntax. Here is a toy sample, not compiling (neither of the three variants of animal_factory function compiles):
enum Error {
UnknownAnimal,
}
trait Animal {
fn bark(&self);
}
struct Dog {}
impl Dog {
fn new() -> Result<Dog, Error> {
Ok(Dog {})
}
}
impl Animal for Dog {
fn bark(&self) {
println!("Bau! Bau!");
}
}
struct Cat {}
impl Cat {
fn new() -> Result<Cat, Error> {
Ok(Cat {})
}
}
impl Animal for Cat {
fn bark(&self) {
println!("Meow! Meow!");
}
}
/*
fn animal_factory(kind: &str) -> Result<impl Animal, Error> {
match kind {
"cat" => Cat::new(),
"dog" => Dog::new(),
_ => Err(Error::UnknownAnimal),
}
}
*/
/*
fn animal_factory(kind: &str) -> Result<impl Animal, Error> {
match kind {
"cat" => {
return Cat::new();
},
"dog" => {
return Dog::new();
},
_ => {
return Err(Error::UnknownAnimal);
},
}
}
*/
fn animal_factory(kind: &str) -> Result<impl Animal, Error> {
if kind == "cat" {
Cat::new()
} else if kind == "dog" {
Dog::new()
} else {
Err(Error::UnknownAnimal)
}
}
fn main() {
let x = animal_factory("cat").unwrap();
let y = animal_factory("dog").unwrap();
}
Any insights? maybe I need to Box things up?