How to return a vector of type T, where T implements trait U?

Hey folks! I am working on a project, where I am using three-d). I want to make use of the struct Gm but add some more information to the struct, hence I create the struct Renderable, which implements the trait Material. This allows me to have renderable be generic of different materials. In the function prepare_objects I want to add some information to the renderables, before passing them to some other function. As you can see, the function returns a vector of Renderable. Here I want to return a vector of renderables, where each element can have a different implementation of Material. How can I write this?

I understand that this solution would require the vector to store elements of dynamic size, but I am not sure how to do this.

To minimize the context for you, I crafted a minimal version:
Minimal version in rust playground

use three_d::{Gm, InstancedMesh, Material};

pub struct Renderable<M>
where
    M: Material,
{
    pub item: Gm<InstancedMesh, M>,
    pub name: String,
    pub is_visible: bool,
}

impl<M: Material> Renderable<M> {
    pub fn new(item: Gm<InstancedMesh, M>, name: String) -> Self {
        Renderable {
            item,
            name,
            is_visible: true,
        }
    }
}

pub fn prepare_objects(
        &self,
        context: &Context,
    ) -> Vec<Box<Renderable<&dyn Material>>> {
todo!()
}

To fix your compiler error, you have to implement Draw for its boxed version, since this isn't done automatically by the compiler:

impl Draw for Box<dyn Draw> {
    fn draw(&self) {
        (**self).draw();
    }
}
3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.