Reputation: 1472
Is it possible to have a trait function that returns any trait object?
Or, can a generic parameter be a trait object type?
trait ToVec<T> {
fn to_vec(&self) -> Vec<&dyn T>;
}
trait TraitA {}
trait TraitB {}
// etc
Upvotes: 0
Views: 105
Reputation: 170899
You can't have &dyn T
, as T
is not a trait. But &dyn ToVec<T>
(or &dyn SomeOtherTrait
) is fine.
In your playground example, Vec<T>
is actually correct because you already have T
as a trait object &dyn TraitA
in the impl
s; but as the error message says, you need to fix lifetimes. E.g. this compiles
trait TraitA {}
trait ToVec<T> {
fn to_vec(&self) -> Vec<T>;
}
impl<'a, T: TraitA> ToVec<&'a dyn TraitA> for (&'a str, &'a T) {
fn to_vec(&self) -> Vec<&'a dyn TraitA> {
vec![
self.1 as &dyn TraitA
]
}
}
but may or may not be what you intended.
Upvotes: 1