Using the default attribute method

Some feature methods have standard implementations that can be overwritten by the developer. How can I use the default implementation for a structure that overwrites the default value?

Example:

trait SomeTrait { fn get_num(self) -> uint; fn add_to_num(self) -> uint { self.get_num() + 1 } } struct SomeStruct; impl SomeTrait for SomeStruct { fn get_num(self) -> uint { 3 } fn add_to_num(self) -> uint { 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? } 
+6
source share
1 answer

Maybe the best solution, but I came up with just to define a dummy structure containing the structure that I want to change, and then I can select the cherries which methods I want to rewrite and which I want to keep the default value. To extend the original example:

 trait SomeTrait { fn get_num(self) -> uint; fn add_to_num(self) -> uint { self.get_num() + 1 } } struct SomeStruct; impl SomeTrait for SomeStruct { fn get_num(self) -> uint { 3 } fn add_to_num(self) -> uint { self.get_num() + 2 } } fn main() { struct SomeOtherStruct { base: SomeStruct } impl SomeTrait for SomeOtherStruct { fn get_num(self) -> uint { 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 data. println!("{}", SomeOtherStruct{base:the_struct}.add_to_num()); } 
+5
source

Source: https://habr.com/ru/post/976730/


All Articles