借用的价值活得不够长,需要静态生命周期

Borrowed value does not live long enough requiring static lifetime

我在这个 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.

内容是:

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(())
}

我不知道为什么 cast requires that text is borrowed for 'static 有人可以帮我解决这个问题吗?我不知道我做错了什么。

TLDR: Fixed version

问题出在你的Container定义中:

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

语句dyn TestTrait等同于dyn TestTrait + 'static,意思是你的trait对象不能包含任何生命周期小于'static.

的引用

为了解决这个问题,你必须用一个不太严格的特性来替换那个特性绑定:

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

现在容器需要 'a,而不是 'static。而且您还必须将该更改应用于实现:

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

相关资源: