Is there any way to call the trait object method particularly

trait Trait {
    fn f(&self);
}

impl<'a> dyn Trait + 'a {
    fn f(&self) {
        print!("1");
    }
}

impl Trait for bool {
    fn f(&self) {
        print!("2");
    }
}

fn main() {
    Trait::f(&true);
    Trait::f(&true as &dyn Trait);
    <_ as Trait>::f(&true);
    <_ as Trait>::f(&true as &dyn Trait);
    <bool as Trait>::f(&true);
}

(Playground)

I thought that one of these might work to call the inherent method on dyn Trait, but they both fail with the compiler error “multiple applicable items in scope.”

<dyn Trait>::f(&true);
(&true as &dyn Trait).f();

It looks like there might be no way to call this inherent method, unless you give it a name that does not conflict with the trait method.

3 Likes

Not right now, though personally I hope this changes. Some comments there point out that a adding a wrapper trait makes it possible to work around (but isn't without downsides).

Despite being titled async everywhere, this series is really about dyn Trait generally and there's some explanation of the historical reasoning behind the "inherent methods are the trait impl" mindset.

1 Like

This would have been my guess too; I'm surprised it doesn't work.

Or at least that the definition of the "inherent" method on the dyn Trait should get a warning that that's a bad idea. (Though this isn't the only inherent thing you can define but not use.)

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.