1

In C++, an overridden virtual member function can call the version defined in its base class:

struct foo {
  virtual void run() {
    printf("printf yeah!\n");
  }
};

struct bar : foo {
  void run() {
    foo::run();
    std::cout << "un-cout-h!" << std::endl;
  }
};

I want to do something similar in Rust. I have a trait containing default method definitions, and I want to reuse those definitions in impls where those methods are overridden:

trait Foo {
    fn run(&self) {
        // do something
    }
}

impl Foo for Bar {
    fn run(&self) {
        // call default implementation of Foo::run()
        // run custom logic
    }
}

How do I do this?


Edit: The proposed solution isn't completely satisfactory. Once I override a method, I intend the overridden implementation not to be usable by third parties.

isekaijin
  • 19,076
  • 18
  • 85
  • 153

1 Answers1

6

You don't.

First of all, Rust doesn't have subclassing like C++ does. Foo::run isn't a thing that exists in a way you can call it. That method body is only used when you implement Foo for a type and don't provide an implementation of the run method. It is effectively copy+pasted by the compiler into each impl where it is needed.

Secondly, the two examples aren't comparable because you've radically changed the meaning. In the C++ case, you're defining an instance method. In the Rust case, you're defining a static method. Instance methods in Rust require an explicit self parameter. Even if that weren't the case, though, it wouldn't change anything about the first point.

If you want to provide some common functionality, you need to write that somewhere else. The simplest way to do this is to use a free function like so:

trait Foo {
    fn run(&mut self) {
        println!("Foo::run()");
    }
}

fn run_base(foo: &mut Foo) {
    println!("run_base()");
}

struct Bar;

impl Foo for Bar {
    fn run(&mut self) {
        run_base(self);
        println!("Bar::run()");
    }
}

fn main() {
    let mut bar = Bar;
    bar.run();
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
DK.
  • 55,277
  • 5
  • 189
  • 162