Is it possible to call a override method in a super method?

Say I write a visitor trait, which looks like:

trait Visitor {
    fn visit(&mut self, a: Node) {
        match a {
            Node::A(n) => self.visit_a(n)
            ...
        }
    }

    fn visit_a(&mut self, a: A);
}

I'd like to reuse the default implementation for visit to do traversal and let it call my customized method visit_a. Is it possible to implement this?

Yes. And that's precisely how you would do it. When structs impl this trait, they only need to provide a definition for visit_a.

impl Visitor for Struct {
    fn visit_a(&mut self, a: A) {
        // ...
    }
}

All methods in a trait always resolve to the one in the impl of the struct. Don't think of it as inheritance and overriding, rather think of it as if the definition of visit is copied and pasted into every impl where you do not explicitly define it.

3 Likes

Got it, so can I treat the method as an overwrite, where there is no dynamic dispatching at all?

Correct. This is all statically dispatched. Though that's a bit orthogonal to the question;

Dynamic dispatching occurs if a function is explicitly written to take a &dyn Visitor (or Box<dyn Visitor>, or other similar pointer type); this is known as a trait object. Even then, when visit is called on the trait object, it will be able to call the methods from each type (because you'll be calling the version of visit that was generated for that specific type), and can even be overridden itself.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.