如何键入参数化不直接使用该类型的结构?

时间:2015-02-22 02:58:18

标签: rust

过去这段代码已编译,但最近不再被接受(我相信自RFC 738以来)。我想对VertexBuffer进行类型参数化,但它实际上并不包含任何顶点,而是GPU保存顶点,结构只保存OpenGL buffer_id

pub struct VertexBuffer<V: Vertex> {
    buffer_id: GLuint,
    num_vertices: usize,
}

new函数填充缓冲区:

impl<V: Vertex> VertexBuffer<V> {
    pub fn new(data: &Vec<V>) -> VertexBuffer<V>
    {
        let buffer_id = unsafe {
            let mut id: GLuint = 0;
            gl::GenBuffers(1, &mut id);
            gl::BindBuffer(gl::ARRAY_BUFFER, id);
            gl::BufferData(gl::ARRAY_BUFFER,
                (mem::size_of::<V>() * data.len()) as GLsizeiptr,
                 mem::transmute(&data[0]),
                 gl::STATIC_DRAW);
            id
        };

        VertexBuffer {
            buffer_id: buffer_id,
            num_vertices: data.len(),
        }
    }
    ....
}

我现在收到这些错误:

src/vertex_buffer.rs:10:25: 10:26 error: parameter `V` is never used
src/vertex_buffer.rs:10 pub struct VertexBuffer<V: Vertex> {

src/vertex_buffer.rs:10:25: 10:26 help: consider removing `V` or using a marker such as `core::marker::PhantomData`
src/vertex_buffer.rs:10 pub struct VertexBuffer<V: Vertex> {

仅供参考,impl中的其他函数(如pre_render()和post_render())使用V类型来完成工作,调用类似

的内容
let attribute_data = Vertex::attribute_data(None::<V>);

1 个答案:

答案 0 :(得分:2)

您还没有显示足够的代码来排除这种情况,所以我建议您将类型转移到函数中:

impl VertexBuffer {
    pub fn new<V: Vertex>(data: &Vec<V>) -> VertexBuffer<V> {
        let buffer_id = unsafe {
            let mut id: GLuint = 0;
            gl::GenBuffers(1, &mut id);
            gl::BindBuffer(gl::ARRAY_BUFFER, id);
            gl::BufferData(gl::ARRAY_BUFFER,
                (mem::size_of::<V>() * data.len()) as GLsizeiptr,
                 mem::transmute(&data[0]),
                 gl::STATIC_DRAW);
            id
        };

        VertexBuffer {
            buffer_id: buffer_id,
            num_vertices: data.len(),
        }
    }
    ....
}

如果您确实需要使用PhantomData,请尝试以下操作:

struct VertexBuffer<V> {
    buffer_id: u32, // or whatever
    num_vertices: u32, // or whatever
    marker: std::marker::PhantomData<V>,
}

impl<V: Vertex> VertexBuffer<V> {
    pub fn new(data: &Vec<V>) -> VertexBuffer<V> {
        let buffer_id = unsafe {
            let mut id: GLuint = 0;
            gl::GenBuffers(1, &mut id);
            gl::BindBuffer(gl::ARRAY_BUFFER, id);
            gl::BufferData(gl::ARRAY_BUFFER,
                (mem::size_of::<V>() * data.len()) as GLsizeiptr,
                 mem::transmute(&data[0]),
                 gl::STATIC_DRAW);
            id
        };

        VertexBuffer {
            buffer_id: buffer_id,
            num_vertices: data.len(),
            marker: std::marker::PhantomData,
        }
    }
    ....
}