特别是,我觉得将 Sphere(Sphere) 放入 Shape 枚举中感觉是错误的,并且以这种方式实现形状的 Volume 似乎是一种迂回的做事方式:
struct Particle {
mass: f64,
shape: Shape
}
enum Shape {
Sphere(Sphere)
}
impl Volume for Shape {
fn calculate_volume(&self) -> f64 {
match self {
Shape::Sphere(sphere) => 4.0 / 3.0 * consts::PI * sphere.radius.powi(3),
_ => panic!("Not valid")
}
}
}
impl Particle {
pub fn calculate_density(&self) -> f64{
self.mass * self.shape.calculate_volume()
}
}
struct Sphere {
radius: f64
}
trait Volume {
fn calculate_volume(&self) -> f64;
}
我之前尝试使用枚举来实现这一点:
enum Shape {
Sphere
}
代替:
enum Shape {
Sphere(Sphere)
}
如果我对上面的代码的倾向是错误的,请告诉我它的用途是什么。请注意,我添加了这段代码,但我什至不知道我在做什么......
编辑:我计划将来添加更多形状,而不仅仅是球体。
这是 Rust 中的常见模式。它类似于使用运行时动态调度的 OOP。这在 Rust 中以
dyn
的形式存在,但在许多情况下,您可以完全按照此处所做的操作——构建一个枚举,然后静态分派:
trait Volume {
fn calculate_volume(&self) -> f64;
}
struct Sphere {
radius: f64
}
impl Volume for Sphere {
fn calculate_volume(&self) -> f64 {
4.0 / 3.0 * consts::PI * self.radius.powi(3)
}
}
enum Shape {
Sphere(Sphere)
}
impl Volume for Shape {
fn calculate_volume(&self) -> f64 {
match self {
Self::Sphere(s) => s.calculate_volume(),
}
}
}
这允许您在
Volume
上绑定通用类型,然后它可以直接接受 Shape
或任何变体(例如 Sphere
)。