Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
875 views
in Technique[技术] by (71.8m points)

rust - Should I use enums or boxed trait objects to emulate polymorphism?

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!(),
            },
        }
    }
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...