我在这个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”。
有谁可以帮助我解决这个问题吗?我不知道我做错了什么。