How to parameterize over a trait itself like a type parameter?

Is it possible to do something like this (not real rust code):

struct List<trait T> {
    mem: NonNull<u8>,
}

impl<trait T> List<T> {
    fn push<U>(&mut self, element: U) where U: T { .. }
}

The code above allows insertion of new element U as long as the element implements the trait T.

Similar to:

  1. Will this ever be possible? (Generic Trait parameters)

It is not possible and there are no active plans to make it possible, but sometimes you can substitute a type for a trait by using a generic trait.

trait Accept<T> {
    ...
}

struct List<T> {
    ...
}

impl<T> List<T> {
    fn push<U>(&mut self, element: U) where U: Accept<T> { .. }
}

Then the caller defines some type Foo and implements Accept<Foo> instead of defining a new trait. Of course, this limits how the trait can differ.

1 Like

Thanks for the reply. In this case, I suppose Accept could be replaced with Unsize trait.

struct List<T: ?Sized> { .. }

impl<T: ?Sized> List<T> {
    pub fn push<U>(&mut self, element: U) where U: Unsize<T> { .. }
}

You're building a list of unsized values? Maybe dyn_vec already does what you want.

2 Likes

Thanks! This is exactly what I wanted.