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

3
我在这个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要求文本被借用为“static”。 有谁可以帮助我解决这个问题吗?我不知道我做错了什么。

1个回答

5
问题出在你的Container定义中:
struct Container {
    buf: Vec<Box<dyn TestTrait>>,
}

dyn TestTrait语句等同于dyn TestTrait + 'static,这意味着您的trait对象不能包含任何生命周期小于'static的引用。

为了解决问题,您需要将该trait限定替换为一个较为宽松的限定:

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

相关资源:


非常感谢! - Sanhu Li
@SanhuLi 如果这个答案对您有帮助,请点击“接受”按钮。 - Svetlin Zarev
啊,我明白了,原来勾选框就是接受按钮。你知道我怎么做吗?我没看到任何地方有按钮可以接受它。昨天我看到一个向上的箭头并点击了它。 - Sanhu Li

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接