如何在特性中使用枚举并在枚举中的结构上实现特性?铁锈

  • 本文关键字:枚举 结构上 铁锈 实现 rust enums
  • 更新时间 :
  • 英文 :


我正在学习Rust,所以这可能是重复的,因为我仍然不知道如何搜索它。我试图制作一个包含不同结构的枚举,由于这些结构有相同的方法但不同的实现,我不知道如何正确地编写特性和实现的类型。这就是我目前所拥有的:

struct Vector2 {
x: f32,
y: f32,
}
struct Vector3 {
x: f32,
y: f32,
z: f32,
}
enum Vector {
Vector2(Vector2),
Vector3(Vector3),
}
trait VectorAdd {
fn add(&self, other: &Vector) -> Vector;
}
impl VectorAdd for Vector2 {
fn add(&self, other: &Vector2) -> Vector2 {
Vector2 {
x: self.x + other.x,
y: self.y + other.y
}
}
}

这段代码不会编译,错误消息也不会让我更清楚。有人可以指导我如何正确编写这段代码吗?或者如果可能的话?

由于您在这里使用泛型,因此不需要枚举来编写特性:

struct Vector2 {
x: f32,
y: f32,
}
struct Vector3 {
x: f32,
y: f32,
z: f32,
}
trait VectorAdd {
fn add(&self, other: &Self) -> Self;
}
impl VectorAdd for Vector2 {
fn add(&self, other: &Vector2) -> Vector2 {
Vector2 {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl VectorAdd for Vector3 {
fn add(&self, other: &Vector3) -> Vector3 {
Vector3 {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
}
}
}

(操场(

您可以基于以下定义实现enum

enum Vector {
Vector2(Vector2),
Vector3(Vector3),
}
impl VectorAdd for Vector {
fn add(&self, other: &Vector) -> Vector {
match (self, other) {
(Self::Vector2(a), Self::Vector2(b)) => Self::Vector2(a.add(b)),
(Self::Vector3(a), Self::Vector3(b)) => Self::Vector3(a.add(b)),
_ => panic!("invalid operands to Vector::add"),
}
}
}

如果变体的数量变大,宏可能会对您有所帮助。

最新更新