小编Ael*_*fyr的帖子

使用可变引用遍历递归结构并返回最后一个有效引用

我试图递归一个节点结构,修改它们,然后返回Node我得到的最后一个。我使用非词法生命周期 RFC 中示例解决了循环中可变引用的问题。如果我尝试将可变引用返回到 last Node,则会出现use of moved value错误:

#[derive(Debug)]
struct Node {
    children: Vec<Node>,
}

impl Node {
    fn new(children: Vec<Self>) -> Self {
        Self { children }
    }
    fn get_last(&mut self) -> Option<&mut Node> {
        self.children.last_mut()
    }
}

fn main() {
    let mut root = Node::new(vec![Node::new(vec![])]);

    let current = &mut root;

    println!("Final: {:?}", get_last(current));
}


fn get_last(mut current: &mut Node) -> &mut Node {
    loop {
        let temp = current; …
Run Code Online (Sandbox Code Playgroud)

reference mutable rust borrowing

5
推荐指数
1
解决办法
559
查看次数

标签 统计

borrowing ×1

mutable ×1

reference ×1

rust ×1