如何在特征函数中发送不同的结构?

How to send different structs in a function of a trait?

enum Property {
    Triangle(TriangleProperty),
    Square(SquareProperty),
}

struct Triangle {
    x: u8,
    y: Vec<u8>,
}

struct Square {
    x: u8,
    y: String,
}

struct TriangleProperty {
    a: u8,
    b: u8,
    c: u8,
}

struct SquareProperty {
    a: u8,
    b: u8,
    c: u8,
    d: u8,
}

trait Shape {
    fn do_magic(&self, p: Property) -> u64;
}

impl Shape for Triangle {
    fn do_magic(&self, p: Property) -> u64 {
        match (p) {
            Triangle(x) => { /* do something with x */ }
            _ => panic("this wont happen"),
        }
    }
}

impl Shape for Square {
    fn do_magic(&self, p: Property) -> u64 {
        match (p) {
            Square(x) => { /* do something with x */ }
            _ => panic("this wont happen"),
        }
    }
}

如您所见,我正在调用 panic,我认为这不是处理此问题的好方法。

这只是一个示例,但我不能在 Triangle 结构中包含 TriangleProperty。因为我在函数 do_magic 中使用 TriangleProperty 作为输入,该函数使用常量不可变 Triangle 结构。所以我能想到的唯一选择是包装在 enum 中。但是有没有更好的方法来做到这一点?

这看起来像是 关联类型的用例:

trait Shape {
    type Property;
    fn do_magic(&self, p: Self::Property) -> u64;
}

impl Shape for Triangle {
    type Property = TriangleProperty;
    fn do_magic(&self, p: Self::Property) -> u64 {
        /* do something with p */
    }
}

impl Shape for Square {
    type Property = SquareProperty;
    fn do_magic(&self, p: Self::Property) -> u64 {
        /* do something with p */
    }
}

当您实施 Shape 时,您可以选择 Self::Property 的类型,并且在 impl 中您可以将其用作具体类型。编译器不允许您将 SquareProperty 传递给 Triangle::do_magic,反之亦然。