How to call associated method of trait object

if method with same name defined for both trait and trait object, how to call it explicitly?

assume trait Foo is defined as:

trait Foo {
    fn bar(&self);

and corresponding trait object's implementation is:

impl dyn Foo {
    fn bar(&self) { // label: bar_obj
        println!("Foo object: bar()");
    fn bar2(&self) { // label: bar2_obj
        println!("Foo object: bar2()")

and trait implementation for u8 as follows:

impl Foo for u8 {
    fn bar(&self) { // label: bar_trait
        println!("Foo trait for u8: bar()");

my question is how to invoke these 2 bar (labeled as bar_obj and bar_trait) respectively?

fn main()
    let n = Box::new(128u8);
    let bn: Box<dyn Foo> = n.clone();; // OK, will call `label: bar_trait`
    bn.bar2(); // OK, will cal `label: bar2_obj`; // Error, mutiple candidates, error E0034

    //; // So how to call `label: bar_obj`?


I couldn't find a way either. Maybe just avoid this situation (where a trait object and its trait have methods with the same name)? It seems somewhat confusing anyways.

1 Like

You can't (without workarounds like a separate trait). Apparently the historical (pre-1.0) reason is partial compiler implementations of Trait for dyn Trait.

Personally I think they should be callable and thus act like other types, but anyway, that's the current situation.

1 Like

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.