zino
zino

Reputation: 1472

Can I define a trait that has a generic function returning a trait object?

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

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=92008c3e799f9c2f9189a0100daa4e1a

Upvotes: 0

Views: 105

Answers (1)

Alexey Romanov
Alexey Romanov

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 impls; 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

Related Questions