我希望消除这里重复的代码,而不必列出每个枚举种类:
use Geometry::*;
let geometry = match (&self.geometry, &other.geometry) {
(Point(a), Point(b)) => Point(*a.interpolate(b, t)),
(Curve(a), Curve(b)) => Curve(*a.interpolate(b, t)),
(EPBox(a), EPBox(b)) => EPBox(*a.interpolate(b, t)),
(_, _) => unimplemented!("Kinds not matching")
};
种类中的类型都实现了
Interpolate
特质,该特质拥有interpolate
方法:enum Geometry {
Point(Point),
Curve(Curve),
EPBox(EPBox)
}
trait Interpolate {
fn interpolate(&self, other: &Self, t: f64) -> Box<Self> {
// ...
}
}
impl Interpolate for Point {}
impl Interpolate for Curve {}
impl Interpolate for EPBox {}
我想做的是类似于这样的事情:
let geometry = match (&self.geometry, &other.geometry) {
(x(a), x(b)) => x(*a.interpolate(b, t)), // and check that a and b impls Interpolate
(_, _) => unimplemented!("Kinds not matching")
};
Box<Self>
,然后解包它 (*a
) 似乎是多余的。 - battlmonstrinterpolate
的返回类型切换为Self where Self: Sized
可以解决问题并消除Box<Self>
。但我的IDE说我需要使用Box... - Jonatan Kallus