Search code examples
rustlifetime

How can I make a variable borrow for 'static?


In vulkano, to create a CPUAccessibleBuffer you need give it some data and the CPUAccessibleBuffer::from_data function requires the data to have the 'static lifetime.

I have some data in &[u8] array (created at runtime) that I would like to pass to that function.

However, it errors with this message

argument requires that `data` is borrowed for `'static`

So how can I make the lifetime of the data 'static ?


Solution

  • You should use CpuAccessibleBuffer::from_iter instead, it does the same thing but does not require the collection to be Copy or 'static:

    let data: &[u8] = todo!();
    
    let _ = CpuAccessibleBuffer::from_iter(
        device,
        usage,
        host_cached,
        data.iter().copied(), // <--- pass like so
    );
    

    Or if you actually have a Vec<u8>, you can pass it directly:

    let data: Vec<u8> = todo!();
    
    let _ = CpuAccessibleBuffer::from_iter(
        device,
        usage,
        host_cached,
        data, // <--- pass like so
    );