[英]"Lifetime in struct : "this value requires that `'1` must outlive `'static`
I am new to the concept of lifetime but I don't understand why the current code gives me an error我对生命周期的概念不熟悉,但我不明白为什么当前代码会给我一个错误
error -> [1]: https://i.stack.imgur.com/v4Yf6.png错误-> [1]: https://i.stack.imgur.com/v4Yf6.png
Code:代码:
pub struct Folder<'a> {
pub name: &'a str,
pub contents: Vec<Box<dyn Executable>>,
pub parent: Box<Option<&'a Folder<'a>>>
}
impl<'a> Folder<'a> {
pub fn new(folder_name: &'a str, json_content: &'a Value) -> Self {
Self {
name: folder_name,
contents: Folder::get_content(json_content),
parent: Box::new(None)
}
}
fn get_content(json_content: &Value) -> Vec<Box<dyn Executable>> {
let elements_in_folder: &Vec<Value> = json_content.as_array().unwrap();
let mut contents: Vec<Box<dyn Executable>> = Vec::new();
for element in elements_in_folder.iter() {
match element["type"].as_str().unwrap() {
"folder" => {
let folder = Folder::new(
element["name"].as_str().unwrap(),
&element["content"],
);
contents.push(Box::new(folder))
}
"command" => contents.push(Box::new(Command::new(&element))),
"combo" => contents.push(Box::new(Combo::new(&element))),
_ => panic!("Folder: field type unknow"),
}
}
contents // THE ERROR IS HERE
}
}
Folder Command and Combo impl Executable文件夹命令和组合 impl 可执行文件
Your contents
is borrowing values from inside the argument.您的
contents
是从参数内部借用值。 You need to make that explicit, with a lifetime constraint.您需要明确说明这一点,并具有生命周期约束。
fn get_content<'a>(json_content: &'a Value) -> Vec<Box<dyn Executable + 'a>> {
...
}
or, equivalently, you can use the anonymous lifetime.或者,等效地,您可以使用匿名生命周期。 The following is equivalent to the above but shorter.
以下等同于上述但更短。
fn get_content(json_content: &Value) -> Vec<Box<dyn Executable + '_>> {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.