Insert generics inside structure

I find it difficult to use Rust traits, so, for example, what is the correct way to do this?

pub struct Cube<R>{
    pub vertex_data: [Vertex;24],
    pub asMesh: gfx::Mesh<R>
}

      

+3


source to share


1 answer


Only generics can be used when defining the structure, but you can use feature boundaries for these generics to restrict them to specific types. I used a suggestion here where

:

trait Vertex {}

struct Mesh<R> {
    r: R,
}

struct Cube<V, R>
    where V: Vertex,
{
    vertex_data: [V; 24],
    mesh: Mesh<R>,
}

fn main() {}

      

You will also want to use these constraints for any method implementations:



impl<V, R> Cube<V, R>
    where V: Vertex,
{
    fn new(vertex: V, mesh: Mesh<R>) -> Cube<V, R> { ... }
}

      

In fact, you will often see only a proposal where

for implementation, not structure. This is because you usually only access the structure via methods, and the structure is opaque to the end user. If you have public fields, it might be worth leaving them in both places.

+4


source







All Articles