Borrowed value does not live long enough requiring static lifetime

Viewed 863

I'm getting this error with a sample code at this rust playground

   Compiling playground v0.0.1 (/playground)
error[E0597]: `text` does not live long enough
  --> src/main.rs:34:38
   |
34 |     let item = NotLongEnough { text: &text };
   |                                      ^^^^^ borrowed value does not live long enough
35 |     let mut wrapper = Container { buf: Vec::new() };
36 |     wrapper.add(Box::new(item));
   |                 -------------- cast requires that `text` is borrowed for `'static`
...
40 | }
   | - `text` dropped here while still borrowed

error: aborting due to previous error

For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground`

To learn more, run the command again with --verbose.

The contents are:

trait TestTrait {
    fn get_text(&self) -> &str;
}

#[derive(Copy, Clone)]
struct NotLongEnough<'a> {
    text: &'a str,
}

impl<'a> TestTrait for NotLongEnough<'a> {
    fn get_text(&self) -> &str {
        self.text
    }
}

struct Container {
    buf: Vec<Box<dyn TestTrait>>,
}

impl Container {
    pub fn add(&mut self, item: Box<dyn TestTrait>) {
        self.buf.push(item);
    }

    pub fn output(&self) {
        for item in &self.buf {
            println!("{}", item.get_text());
        }
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let text = "test".to_owned();
    let item = NotLongEnough { text: &text };
    let mut wrapper = Container { buf: Vec::new() };
    wrapper.add(Box::new(item));
    wrapper.output();

    Ok(())
}

I have no clue why cast requires that text is borrowed for 'static Could someone please help me with this? I've no idea what I've done wrong.

1 Answers

TLDR: Fixed version

The problem is in your Container definition:

struct Container {
    buf: Vec<Box<dyn TestTrait>>,
}

The statement dyn TestTrait is equivalent to dyn TestTrait + 'static, meaning that your trait objects must not contain any references with lifetime less than 'static.

In order to fix the problem, you have to replace that trait bound with a less strict one:

struct Container<'a> {
    buf: Vec<Box<dyn TestTrait + 'a>>,
}

Now instead of 'static, the container requires 'a. And you have to apply that change to the implementation as well:

   pub fn add(&mut self, item: Box<dyn TestTrait + 'a>) { // notice the new trait-bound
        self.buf.push(item);
   }

Relevant resources:

Related