在结构中嵌入泛型

Embed generics inside struct

我在使用 Rust traits 时发现了一些困难,例如哪种方法是正确的?

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

您只能在定义结构时使用泛型,但您可以对这些泛型使用 trait bounds 以将其限制为特定类型。在这里,我使用了 where 子句:

trait Vertex {}

struct Mesh<R> {
    r: R,
}

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

fn main() {}

您还想在任何方法实现上使用这些界限:

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

事实上,您经常只会在实现中看到 where 子句,而不是结构。这是因为您通常只能通过方法访问结构,而结构对最终用户来说是不透明的。如果您有 public 个字段,那么可能值得在两个地方都保留边界。