某些特征方法具有可由实施者覆盖的默认实现。如何使用覆盖默认值的结构的默认实现?
例如:
trait SomeTrait {
fn get_num(&self) -> i32;
fn add_to_num(&self) -> i32 {
self.get_num() + 1
}
}
struct SomeStruct;
impl SomeTrait for SomeStruct {
fn get_num(&self) -> i32 {
3
}
fn add_to_num(&self) -> i32 {
self.get_num() + 2
}
}
fn main() {
let the_struct = SomeStruct;
println!("{}", the_struct.add_to_num()); // how can I get this to print 4 instead of 5?
}
答案 0 :(得分:5)
我提出的一个解决方案是定义一个包含我想要更改的结构的虚拟结构。然后,我可以选择要覆盖哪些方法以及我希望保留哪些方法作为默认值。
扩展原始示例:
trait SomeTrait {
fn get_num(&self) -> i32;
fn add_to_num(&self) -> i32 {
self.get_num() + 1
}
}
struct SomeStruct;
impl SomeTrait for SomeStruct {
fn get_num(&self) -> i32 {
3
}
fn add_to_num(&self) -> i32 {
self.get_num() + 2
}
}
fn main() {
struct SomeOtherStruct {
base: SomeStruct,
}
impl SomeTrait for SomeOtherStruct {
fn get_num(&self) -> i32 {
self.base.get_num()
}
//This dummy struct keeps the default behavior of add_to_num()
}
let the_struct = SomeStruct;
println!("{}", the_struct.add_to_num());
//now we can call the default method using the original struct's data.
println!("{}", SomeOtherStruct { base: the_struct }.add_to_num());
}