简体   繁体   English

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

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

I'm learning Rust so this might be a duplicate, since I'm still not sure how to search this.我正在学习 Rust 所以这可能是重复的,因为我仍然不确定如何搜索它。 I tried to make a enum that contains different structs and since those structs have same methods but different implementation, I can't figure out how to properly write the types for the trait and the implementation.我试图创建一个包含不同结构的枚举,并且由于这些结构具有相同的方法但不同的实现,我无法弄清楚如何正确编写特征和实现的类型。 This is what I have so far:这是我到目前为止所拥有的:

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
        }
    }
}

This code does not compile, and the error messages don't make it clearer for me.此代码无法编译,并且错误消息并没有让我更清楚。 Anyone can guide me how to write this properly?任何人都可以指导我如何正确地写这个? or if it's even possible?或者如果它甚至可能?

Since you are using generics here, you don't need the enum to write the trait:由于您在这里使用 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,
        }
    }
}

( playground ) 操场

You can implement the enum based on this definition:您可以根据此定义实现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"),
        }
    }
}

Macros may help you if the number of variants gets large.如果变体数量变大,宏可能会对您有所帮助。

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

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