Reputation: 73
I find difficulties when using Rust traits, so for example which is the correct way to do this?
pub struct Cube<R>{
pub vertex_data: [Vertex;24],
pub asMesh: gfx::Mesh<R>
}
Upvotes: 4
Views: 917
Reputation: 431489
You can only use generics when defining the struct, but you can use trait bounds on those generics to restrict it to specific types. Here, I've used the where
clause:
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 those bounds on 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 frequently will only see the where
clause on the implementation, not the struct. This is because you normally only access the struct through the methods, and the struct is opaque to the end user. If you have public fields it may be worth leaving the bound in both places though.
Upvotes: 6