2 ms·
Man. The documentation did not make that clear at all. Was this added in 1.0? A question (In C++ syntax, as I'm not a Rust programmer): How would one call Anim
by simoncion 11y ago
Man. The documentation did not make that clear at all. Was this added in 1.0?
A question (In C++ syntax, as I'm not a Rust programmer): How would one call Animal::talk inside Dog::talk? The obvious thing (commenting out the println and adding Animal::talk(self) ) causes infinite recursion. The other vaguely obvious thing ( Animal.talk(self); ) is a syntax error, which makes sense.
Edit: I'm referring to the code at the linked Rust By Example page.
- heinrich5991 11y agoThe feature was added way before 1.0, if you're talking about the documentation, then I have no idea. There is no way to call the overwritten `Animal::talk`.
- jdub 11y agoI thought you could do this: Animal::talk(self);
- chrismorgan 11y agoThere is no such thing as `Animal::talk`. It does not exist. `Animal::talk` is purely shorthand for `<_ as Animal>::talk`, meaning that it is a specific type’s implementation of the `talk` method. In the case of `Animal::talk(dog)` where `dog` is of type `&Dog`, the `_` can be inferred to be `Dog`, and so `Animal::talk(dog)` is equivalent to `Dog::talk(dog)` and `<Dog as Animal>::talk(dog)`. The default implementation, if overridden, does not exist for the given type.
- deleted 11y ago[deleted]
- ryeguy 11y agoNo, this feature has existed a long time. Here's a post from 2012 showing it's use: http://pcwalton.github.io/blog/2012/08/08/a-gentle-introduction-to-traits-in-rust/ http://pcwalton.github.io/blog/2012/08/08/a-gentle-introduct...
- arielby 11y ago`Animal::talk(self)` is shorthand for `<Self as Animal>::talk(self)` - i.e. it calls the overridden method. If you want to reuse the supertrait method, you have to implement it as a generic method outside of the trait, and call it from the default implementation: pub fn super_talk<T:Animal>(this: &T) { println!("{} says {}", this.name(), this.noise()); } trait Animal { //... fn talk(&self) { super_talk(self) } }