How to make mutable pointer to field of node of tree and mutate it? [duplicate]

空扰寡人 提交于 2019-12-31 04:52:27

问题


I want to find some node in the tree and I need a pointer to the container of nodes: &mut Vec<Node>

struct Node {
    c: Vec<Node>,
    v: i32,
}

impl Node {
    pub fn new(u: i32, n: Node) -> Node {
        let mut no = Node {
            c: Vec::new(),
            v: u,
        };

        no.c.push(n);

        no
    }
}

fn main() {
    let mut a = Node::new(1,
        Node::new(2,
        Node::new(3,
        Node::new(4,
        Node::new(5,
        Node {
            c: Vec::new(),
            v: 6,
        })))));

    let mut p: &mut Vec<Node> = &mut a.c;

    while p.len() > 0 {
        p = &mut p[0].c;
    }

    p.push(Node {
        c: Vec::new(),
        v: 7,
    });
}

回答1:


You need a temporary variable to calm down the borrow checker:

while p.len() > 0 {
    let t = p;
    p = &mut t[0].c;
}

Or:

while p.len() > 0 {
    p = &mut {p}[0].c;
}


来源:https://stackoverflow.com/questions/37904071/how-to-make-mutable-pointer-to-field-of-node-of-tree-and-mutate-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!