Emil Sahlén
Emil Sahlén

Reputation: 2130

Using static reference in struct with non-static lifetime

In the following example:

fn send(_data: &'static mut [u8]) {
    unimplemented!();
}

struct Device {
    buffer: &'static mut [u8],
}

impl Device {
    fn new(buffer: &'static mut [u8]) -> Device {
        Device { buffer }
    }

    fn send(&mut self) {
        send(self.buffer);
    }
}

static mut BUFFER: [u8; 128] = [0; 128];

fn main() {
    unsafe {
        let mut device = Device::new(&mut BUFFER);
        device.send();
    }
}

The compiler complains:

error[E0521]: borrowed data escapes outside of method
  --> src/main.rs:15:9
   |
14 |     fn send(&mut self) {
   |             ---------
   |             |
   |             `self` is a reference that is only valid in the method body
   |             let's call the lifetime of this reference `'1`
15 |         send(self.buffer);
   |         ^^^^^^^^^^^^^^^^^
   |         |
   |         `self` escapes the method body here
   |         argument requires that `'1` must outlive `'static`

I do understand what it is saying, that self obviously does not outlive whatever the reference it contains. However, why is this a problem? The buffer will still live on even when self dies?

Upvotes: 1

Views: 29

Answers (0)

Related Questions