使用enum
Axes
来限制Coordinate
和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
链接struct
Coordinate
和Quaternion
:
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) -> () { }
}
在这种情况下,struct
的特征是否更容易访问和更有效?我对在什么情况下使用哪种感到困惑。
答案 0 :(得分:4)
根据情况使用特征和枚举之间的最大区别之一是它们的可扩展性。如果将Axes
设为枚举,则这两个选项将硬编码到类型中。如果要添加某种轴的第三种形式,则必须修改类型本身,这可能涉及使用Axes
对代码进行大量修改(例如,在{{1} },可能需要更改)。另一方面,如果使Axes
为特征,则可以通过仅定义新类型并编写适当的实现方式来添加其他类型的轴,而无需完全修改现有代码。这甚至可以从库外部完成,例如由用户。
要考虑的另一重要事项是您需要对结构的内部进行多少访问。使用枚举,您可以完全访问结构中存储的所有数据。如果您想编写一个可以使用特征同时在Axes
和Coordinate
上运行的函数,那么您唯一可以执行的操作就是Quaternion
特征中描述的那些功能(在Axes
和Shift
)。例如,给出您提供的Fold
的实现,您将无法通过Axes
接口简单地检索(X,Y,Z)
元组。如果需要在某个时候这样做,则必须添加一个新方法。
在不了解您计划如何使用这些类型的更多信息的情况下,很难确定这些选项中哪个是更好的选择,但是如果是我,我可能会使用一个枚举。最终,它很大程度上取决于偏好,但是希望这会使您对做出决定时要考虑的事情有所了解。