如何修复以下代码中的生命周期错误?

问题描述 投票:0回答:1

这是代码

pub struct List<'a> {
    node: Option<Node<'a>>,
    list_vec: Vec<Node<'a>>,
}


pub struct Node<'a> {
    data: String,
    next: Option<&'a Node<'a>>,
}


impl List<'_> {
    fn add(&mut self, val: String, referenced_node: &Node){
        self.node = Some(Node {
            data: String::from(String::from(val)),
            next: Some(referenced_node), // I was expecting to have reference to original variable which i transferred via new_node
        });
}

我期望存储对原始变量的引用,正如我在代码注释中所说的那样

rust
1个回答
0
投票

将生命周期

'a
与您放入
List
中的引用相关联:

//   v        v
impl<'a> List<'a> {
    //                                               v
    fn add(&mut self, val: String, referenced_node: &'a Node) {
        self.node = Some(Node {
            data: String::from(String::from(val)),
            next: Some(referenced_node), // I was expecting to have reference to original variable which i transferred via new_node
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.