我有使用SemVer版本化的数据。我具有SemVer要求的功能,例如它们支持版本[1.1、2.0)。在C ++中,我可以执行以下操作:
struct Data_v1_0 {
// Added in V1.0
int a;
};
struct Data_v1_1 : public Data_v1_0 {
// Added in V1.1
int b;
}
void foo(const Data_v1_0& data) {
// Supports [1.0, 2.0)
print(data.a);
}
void bar(const Data_v1_1& data) {
// Supports [1.1, 2.0)
print(data.b);
}
考虑到它没有继承,是否有办法在Rust中做类似的事情?
您可以为此使用特征:
trait DataV1_0 {
fn a(&self) -> i32;
}
trait DataV1_1: DataV1_0 {
fn b(&self) -> i32;
}
struct Data {
a: i32,
b: i32,
}
impl DataV1_0 for Data {
fn a(&self) -> i32 {
self.a
}
}
impl DataV1_1 for Data {
fn b(&self) -> i32 {
self.b
}
}
fn foo(data: &dyn DataV1_0) {
println!("a: {}", data.a());
}
fn bar(data: &dyn DataV1_1) {
println!("b: {}", data.b());
}
我们使用特征继承来替换此处的结构,并使用特征方法访问字段。我的示例是只读的,但是您也可以实现setter方法。