我应该使用枚举还是盒装 trait 对象来模拟多态性? [英] Should I use enums or boxed trait objects to emulate polymorphism?

查看:19
本文介绍了我应该使用枚举还是盒装 trait 对象来模拟多态性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用枚举Axes 来限制CoordinateQuaternion:

Using the enum Axes to confine Coordinate and Quaternion:

#[derive(Clone)]
pub enum Axes {
    Coordinate {
        x: f64,
        y: f64,
        z: f64,
        reserve: Vec<f64>,
    },
    Quaternion {
        x: f64,
        y: f64,
        z: f64,
    },
}

impl Axes {
    pub fn shift(&mut self, Sample: &Axes) -> () {
        let Dup: Axes = self.clone();
        match Dup {
            Axes::Coordinate { x, y, z, reserve } => match &Sample {
                Axes::Coordinate { x, y, z, reserve } => {
                    *self = Axes::Coordinate {
                        x: *x,
                        y: *y,
                        z: *z,
                        reserve: reserve.to_vec(),
                    };
                }
                _ => panic!(),
            },
            Axes::Quaternion { x, y, z } => match &Sample {
                Axes::Quaternion { x, y, z } => {
                    *self = Axes::Quaternion {
                        x: *x,
                        y: *y,
                        z: *z,
                    };
                }
                _ => panic!(),
            },
        }
    }
}

使用特征Axes 来链接CoordinateQuaternion 结构:

Using the trait Axes to link the Coordinate and Quaternion structs:

pub trait Axes {
    fn shift(&mut self, Sample: &Axes) -> ();
    fn fold(&mut self, Sample: &Axes) -> ();
}

pub struct Coordinate {
    pub x: f64,
    pub y: f64,
    pub z: f64,
    pub reserve: Vec<f64>,
}

pub struct Quaternion {
    pub x: f64,
    pub y: f64,
    pub z: f64,
}

impl Axes for Coordinate {
    fn shift(&mut self, Sample: &Axes) -> () {}
    fn fold(&mut self, Sample: &Axes) -> () {}
}

impl Axes for Quaternion {
    fn shift(&mut self, Sample: &Axes) -> () {}
    fn fold(&mut self, Sample: &Axes) -> () {}
}

在这种情况下,在结构上实现的特征是否更易于访问和更高效?我对使用哪种以及在什么情况下使用感到困惑.

Is a trait implemented on structs more accessible and more efficient in this case? I am confused of which to use and in what cases.

推荐答案

针对您的情况使用特征和枚举的最大区别之一是它们的可扩展性.如果将 Axes 设为枚举,则这两个选项将硬编码到类型中.如果您想添加某种第三种形式的轴,则必须修改类型本身,这可能涉及对使用 Axes 的代码进行大量修改(例如,您在 Axes 上匹配的任何地方code>Axes 可能需要更改).另一方面,如果你让 Axes 成为一个 trait,你可以通过定义一个新类型并编写适当的实现来添加其他类型的轴,而根本不需要修改现有代码.这甚至可以从图书馆外部完成,例如由用户.

One of the big differences between using traits and enums for your situation is their extensibility. If you make Axes an enum, then the two options are hardcoded into the type. If you want to add some third form of axis, you'll have to modify the type itself, which will probably involve a lot of modifications to the code with uses Axes (e.g. anywhere you match on an Axes will probably need to be changed). On the other hand, if you make Axes a trait, you can add other types of axes by just defining a new type and writing an appropriate implementation, without modifying existing code at all. This could even be done from outside of the library, e.g. by a user.

另一个需要考虑的重要事项是您需要对结构内部进行多少访问.使用枚举,您可以完全访问存储在结构中的所有数据.如果您想编写一个可以使用特征对 CoordinateQuaternion 进行操作的函数,那么您将能够执行的唯一操作是 中描述的操作>Axes 特性(在本例中为 ShiftFold).例如,给出您给出的 Axes 的实现,您将无法通过 Axes 简单地检索 (X,Y,Z) 元组 界面.如果您在某个时候需要这样做,则必须添加一个新方法.

The other important thing to consider is how much access you need to the internals of the structs. With an enum, you get full access to all the data stored within the struct. If you want to write a function which can operate on both Coordinate and Quaternion using a trait, then the only operations you will be able to perform are those described in the Axes trait (in this case Shift and Fold). For instance, giving the implementation of Axes you gave, there would be no way for you to simply retrieve the (X,Y,Z) tuple via the Axes interface. If you needed to do that at some point, you would have to add a new method.

如果不知道更多关于您打算如何使用这些类型的信息,很难确定这些选项中的哪一个是更好的选择,但如果是我,我可能会使用枚举.归根结底,这主要取决于偏好,但希望这能让您了解在做出决定时需要考虑的各种事情.

Without knowing more about how you plan to use these types it's difficult to say for sure which of these options is the better choice, but if it were me I would probably use an enum. Ultimately, it comes down largely to preference, but hopefully this will give you some idea of the sorts of things to be thinking about when making your decision.

这篇关于我应该使用枚举还是盒装 trait 对象来模拟多态性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆