boxme
December 15, 2024, 3:35am
1
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
system
Closed
March 15, 2025, 4:14am
3
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.