Rust中是否有一种方法可以从函数中返回实现某些特征的类型(我不需要实例,但需要类型)。诸如此类(不适用于当前形式):
trait MyTrait {
fn sum(&self, val: i64) -> i64;
}
#[derive(Debug)]
struct X {
x: i64,
}
impl MyTrait for X {
fn sum(&self, val: i64) -> i64 {
self.x + 2 * val
}
}
#[derive(Debug)]
struct Y {
x: i64,
}
impl MyTrait for Y {
fn sum(&self, val: i64) -> i64 {
self.x + 3 * val
}
}
fn from_name(name: &str) -> MyTrait {
match name {
"X" => X,
"Y" => Y,
_ => panic!("Unknown name")
}
}
fn main() {
let x = X{x: 21};
let y = Y{x: 42};
// This does not work, it is just to show the idea
let z = from_name("X"){x: 10};
println!("x {:?}", x.sum(3));
println!("y {:?}", y.sum(3));
println!("z {:?}", z.sum(3));
}
最佳答案
与您要求的最接近的是工厂功能:
fn from_name(name: &str) -> Box<Fn(i64) -> Box<MyTrait>> {
match name {
"X" => Box::new(|x| Box::new(X{x: x})),
"Y" => Box::new(|x| Box::new(Y{x: x})),
_ => panic!("Unknown name"),
}
}
fn example() -> i64 {
let factory = from_name("X");
let z = factory(10);
z.sum(10)
}
from_name
返回一个函数,该函数返回一个对象。