2

How can a struct implement a trait method but also call the default version of that method?

pub trait MyTrait {
    fn do_it(&self) {
        println!("I am doing it the default way.");
    }
}

pub struct MyStruct;

impl MyTrait for MyStruct {
    fn do_it(&self) {
        println!("Doing it my way.");
        //Call default method
        self.MyTrait::do_it(); //Not worky
    }
}

fn main() {
    let m = MyStruct;

    m.do_it();
}
RajV
  • 6,860
  • 8
  • 44
  • 62
  • Hi, I saw that answer before posting. It is the same question. But the answer is more of a work around. Incidentally "It can not be done right now in Rust" will be a good answer to these questions. – RajV Nov 30 '15 at 15:48
  • Hi @RajV, what you're trying to do is reuse code through inheritance. Rust (and the community) has decided that this is generally not a good idea. The answer you saw is not a "work around" that's the idiomatic way to do this. You'll probably find this thread (https://users.rust-lang.org/t/oop-how-to-override/1980/4) helpful as well as the linked wikipedia article on composition over inheritance. – Wesley Wiser Nov 30 '15 at 17:57
  • If you want a workaround then it might be prettier to add two separate methods to the trait. `pub trait MyTrait { fn do_it_default(&self) { ....} fn do_it(&self){self.do_it_default() }}` – nielsle Nov 30 '15 at 18:00
  • @nielsle yeah, that's the approach I finally went with. – RajV Nov 30 '15 at 19:47
  • Hi @Wesley, as I understand things, inheritance via composition applies to struct inheritance where data/state reuse is the goal. Reuse of trait methods is a slightly different topic. I have seen discussion (RFC 1210) about making it easier to reuse a default method. http://stackoverflow.com/a/31462293/1036017 – RajV Nov 30 '15 at 19:47
  • another nice approach https://stackoverflow.com/a/56311216/4247851 – Shanavas M May 26 '19 at 06:35

0 Answers0