Implementing a function for a trait developer with dynamic and static dispatch

I want the foo function to take an instance of a type that implements attribute A I always prefer to use generics to have static dispatch:

 trait A {} fn foo<T: A>(t: T) {} 

However, this approach introduces some inflexibility, I can not pass the attribute object, as here:

 trait A {} fn foo(t: &A) {} 

The fact is that sometimes I know the type, and sometimes not. Is there a way to have dynamic dispatch for feature objects and static dispatch to determine compile-time types without doing it twice?

+5
source share
1 answer

It is really possible. One option is to explicitly implement A for reference types:

 impl<'a, T: A + ?Sized> A for &'a T {} 

The argument becomes a sign of the T = &A object, but at the same time it is a static dispatch for well-known developers of A The following code should now compile:

 fn foo<T: A>(a: T) {} struct MyA; impl A for MyA {} fn main() { foo(MyA{}); foo(&MyA{}); foo(&MyA{} as &A); } 

If you are ready to always pass a leverage argument, you can also do this:

 fn foo<T: A + ?Sized>(a: &T) {} 

The argument becomes a feature of the object T = A

+6
source

Source: https://habr.com/ru/post/1263215/


All Articles