我试图用RUST编写一个函数来构建不同类型的对象(所有相同特征的实现),但我遇到了麻烦,不知道我是在try 做一些非法的事情,还是只是没有掌握正确的语法. 以下是一个未编译的玩具样例(Animal_Factory函数的三个变体都没有编译):
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();
}
有什么见解吗?也许我需要把东西装起来?