如何使可变指针指向树节点的字段并对其进行变异?

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

我想在树中找到一些节点,我需要一个指向节点容器的指针:&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,
    });
}

您需要一个临时变量来让借用检查器平静下来:

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

或者:

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