d9ngle
d9ngle

Reputation: 1469

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?

Upvotes: 0

Views: 52

Answers (1)

Peter Hall
Peter Hall

Reputation: 58735

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.

Upvotes: 1

Related Questions