Dyn trait vs impl trait as function parmeter

New to rust and I have been using dynamic dispatch as a function parameter type. But I recently found out that you can do the same with impl Trait.

fn your_func(param: Arc<dyn YourTrait>) {}

vs

fn your_func(param: impl YourTrait) {}

I'd love to learn about when to use one over the other. If you have more than 1 implementation of YourTrait are you still able to do fn your_func(param: impl YourTrait) {}?

Yes.

Use dyn Trait when you want dynamic dispatch. Use impl Trait when you want static dispatch.

Argument-Position impl Trait (APIT) is a gnarly shorthand for generic parameters. You might consider using this instead:

fn your_func<T: YourTrait>(param: T) {}

// or even...

fn your_func<T:>(param: T)
where
    T: YourTrait,
{}
1 Like