Dynamic dispatch associated function

Is there a way to achieve this:

trait Trait {
    fn associated_function() where Self: Sized;
}

impl Trait for String {
    fn associated_function() {
    }
}

fn main() {
    let s = String::new();

    call(&s);
}

fn call(s: &dyn Trait) {
    Trait::associated_function();
}

I actually use a method (with &self parameter), but it’s unless and, the worth, it’s complicate nested implementations.

You could introduce a second trait which is implemented for all T: Trait and who's associated_function() method (which takes &self) just calls <Self as Trait>::associated_function().

That way the second trait can act as an object-safe trampoline to the real implementation.

4 Likes
fn call(s: &dyn Trait, t: &dyn Trait) {
    Trait::associated_function()
}

In the code above, how would call(&foo, &bar) know whether to call foo's associated function or bar's?

1 Like

Here's @Michael-F-Bryan's suggestion fleshed out.

2 Likes

Thanks for your help. That works fine with my example, but it’s not applicable with my existing code :frowning_face:

What's the difference that makes it not apply?

1 Like

I don’t know why, but the compiler still requires my trait be object safe (E0038) additionally that implies to have a third trait that combine the two others for functions arguments.

My code is here: elephantry/to_sql.rs at ty-associated-function · elephantry/elephantry · GitHub

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.