Chad
Chad

Reputation: 1530

call trait method when struct method has same name

In the following code:

pub trait Thinger {
    fn print_thing(&self) where Self: core::fmt::Debug {
        println!("trait method: {:?}", self);
    }
}

#[derive(Debug)]
pub struct Thing(f64);

impl Thing {
    fn print_thing(&self) where Self: core::fmt::Debug {
        println!("method: {:?}", self);
    }
}

impl Thinger for Thing {}

fn main() {
    let thing = Thing(3.14);
    thing.print_thing();
}

how do I call Thinger's print_thing method?
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0717f5615e10e3a1349f6db9cb9c3306

I've seen this in The Book, but I can't find it anywhere.

Upvotes: 0

Views: 937

Answers (2)

Aleksander Krauze
Aleksander Krauze

Reputation: 6081

Thinger::print_thing(&thing)

<Thing as Thinger>::print_thing(&thing)

Here is the fragment of The Book you have been referring to.

Upvotes: 4

Chad
Chad

Reputation: 1530

Aleksander Krauze nailed it, but there is another way to do it for completeness:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4450b905f10198967090c8f56e3acfeb

Thinger::print_thing(&thing);

Upvotes: 0

Related Questions