In Rust, how do you explicitly tie the lifetimes of two objects together, without referencing eachother?

前端 未结 1 1223
情歌与酒
情歌与酒 2021-01-19 12:07

The specific case where I ran into this was in using OpenGL, writing structs for a VertexBuffer and VertexArray. Each struct is, in e

1条回答
  •  無奈伤痛
    2021-01-19 12:51

    This is one of the primary use cases for the PhantomData type, as demonstrated there in an example.

    Applied to this case, you’ll end up with something like this:

    use std::marker::PhantomData;
    
    struct VertexArray<'a> {
        id: GLuint,
        vbo_lifetime: PhantomData<&'a VertexBuffer>,
    }
    

    And instantiation will be something like this:

        fn make<'a>(&'a self) -> VertexArray<'a> {
            VertexArray {
                id: …,
                vbo_lifetime: PhantomData,
            }
        }
    

    (This is eliding the generic type, allowing it to be inferred; you could also write PhantomData::<&'a VertexBuffer>.)

    0 讨论(0)
提交回复
热议问题