繁体   English   中英

如何在特征中使用枚举并在枚举中的结构上实现特征? Rust

[英]How can I use enum in a trait and implement trait on structs that are in the enum? Rust

我正在学习 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
        }
    }
}

此代码无法编译,并且错误消息并没有让我更清楚。 任何人都可以指导我如何正确地写这个? 或者如果它甚至可能?

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

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"),
        }
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM