The parameter type `T` may not live long enough

Hello there, I'm newbie in rust, I've just finished reading rust book. Now I'm trying to draw simple quad using wgpu-rs. I'm trying to make some abstractions over it, and there is how I'm creating a buffer:

pub struct Gapi<'a> {
    _init_encoder: &'a mut wgpu::CommandEncoder,
    device: &'a wgpu::Device,
}

trait Geometry<'a> {
    fn create_vertex_buffer<T>(&mut self, length: usize, data: &'a [T]) -> Buffer
    where
        T: Copy;
}

impl<'a> Geometry<'a> for Gapi<'a> {
    fn create_vertex_buffer<T>(&mut self, length: usize, data: &'a [T]) -> Buffer
    where
        T: Copy,
    {
        let buffer = self
            .device
            .create_buffer_mapped(length, wgpu::BufferUsage::VERTEX)
            .fill_from_slice(&data);

        Buffer { buffer }
    }
}

When I try to compile this I get the error. I can't understand, why rust think, that parameter type will not live long enough. I've solved the problem by adding + 'static to where statement, but I don't understand - what exactly does it mean. In my little example I want to be sure, that data will live while Gapi lives, but I don't whant it to be static.

T: 'static does not mean that the value needs to be static. This has been asked numerous times here, please make some reaearch.

okay, thanks, I've found the answer.

I can't comment on wgpu-rs specific stuff, but here's something I noticed:

This trait combined with this impl seems implausible to me. If create_vertex_buffer is meant to copy stuff out of data, as the T: Copy bound suggests, then there's no reason why the lifetime of data should be the same as the parameter of Gapi because you're not keeping the reference around after create_vertex_buffer. You might as well put the parameter on create_vertex_buffer itself:

trait Geometry {
    fn create_vertex_buffer<'a, T>(&mut self, length: usize, data: &'a [T]) -> Buffer
    where T: Copy;
}

impl<'a> Geometry for Gapi<'a> { ... }

or, using lifetime elision to reduce the verbosity a bit,

trait Geometry {
    fn create_vertex_buffer<T>(&mut self, length: usize, data: &[T]) -> Buffer
    where T: Copy;
}

impl Geometry for Gapi<'_> { ... }

If create_vertex_buffer does store references to data inside self, you may ignore this post.

Yeah, you are right, I've updated trait, thanks.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.