Define function pointer with an argument that implements a trait

Hey guys. This is giving me a bit of headache. I'd like to define a function pointer where a function accepts an argument that implements a trait.

trait Context {
    fn echo();
}
struct App {
    resolver: fn(&str, impl Context) -> usize, // accepts two arguments `&str` and an argument of `Context` 
}

I can't find any documentation on this. Thoughts?

Hi,

as far as I'm aware all trait functions would need the self parameter for the contained functions.
The syntax to pass a trait would be dyn Trait instead of impl Trait. As far as I'm aware the impl indicates to the compiler that the actual type is inferred from the inner contents of a function, meaning this is typically used as a function returning parameter.

The working code of your example could like this:

trait Context {
    fn echo(&self);
}
struct App {
    resolver: fn(&str, dyn Context) -> usize, // accepts two arguments `&str` and an argument of `Context` 
}
1 Like

impl Trait in the argument position is the syntax for generic function; in other words, you want resolver to be of type <T: Context>(&str, T) -> usize. But this is not a type from the Rust's point of view - it is a family of types, since generics are monomorphized.

3 Likes

Ow, yes! I forgot the self in fn echo. Fixed.
Thanks for your quick responses!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.