Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust inheritance: call parent method

Tags:

rust

How does Rust call "parent method"? Like this in Java:

public class parent{
    ...
    public void doSomething(){
        System.out.println("Parent method");
    }
}
public class child extends parent{
    ...
    public void doSomething(){
        super.doSomething();
        System.out.println("Child method.");
    }
}

In Go, we can simulate it by anonymous fields in struct:

type parent struct{}

func (self *parent) doSomething() {
    fmt.Println("parent method")
}

type child struct {
    parent
}

func (self *child) doSomething() {
    self.parent.doSomething()
    fmt.Println("child method")
}
func main() {
    var c1 child
    c1.doSomething()
}

How to simulate it in Rust? Thanks!

like image 487
sunny2016 Avatar asked Sep 07 '13 14:09

sunny2016


1 Answers

It's not quite the same under the hood, but something like

trait DoThings {
    fn do_something(&self); 
}

struct Parent;

impl DoThings for Parent {
    fn do_something(&self) { println("doing something"); }
}

struct Child {
    parent: Parent
}

impl DoThings for Child {
    fn do_something(&self) { 
        self.parent.do_something();
        println("child");
    }
}

fn main() {
    let c = Child { parent: Parent };
    c.do_something();
}

There are a few proposals for making parts of this automatic (e.g. if we wanted to just call the parent's method directly, i.e. don't override the method in the child, then currently one has to explicitly call the parent's method oneself).

like image 126
huon Avatar answered Oct 18 '22 15:10

huon