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!
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With