'How to call the more specific method of struct instead of trait?
There's an external crate which implement a trait but overrides it as well on the struct too:
// external crate
struct Dog;
impl Talker for Dog {
fn speak(&self, t: &str) {
println!("dog says: {}", t);
}
}
impl Dog {
fn speak(&self) {
println!("woof");
}
}
Now from my own code, I'm looking to access the .speak() method which is directly defined on the structure itself. However since I have use external::Talker, the only speak method I can call is speak(&str).
I have also tried:
(d as &Dog).speak();
-- this function takes 1 arguments but 0 arguments were supplied
How can I access the more specific method?
Solution 1:[1]
Postfix method call syntax like d.speak() is syntactic sugar for:
<Dog as Talker>::speak(&d);
or
Dog::speak(&d);
Depending which is in scope. If both are in scope, the inherent method (ie. the one directly implemented for the Dog type) is prefered over the trait implementation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Hall |
