I want to have a function foo
taking an instance of a type which implements a trait A
. I always prefer to use generics in order to have static dispatch:
trait A {}
fn foo<T: A>(t: T) {}
However, this approach introduces some inflexibility, I can't pass a trait object like here:
trait A {}
fn foo(t: &A) {}
The thing is, sometimes I know the type and sometimes not. Is there a way to have both dynamic dispatch for trait objects and static dispatch for compile time known types while not implementing things twice?