无法将x借为可变的,因为x也被借为不可变的

时间:2019-11-21 09:01:05

标签: rust borrow-checker

我知道这个错误是什么意思,我只是不知道如何解决这个难题。简短的背景-我的应用程序中需要树形结构,我发现Rust不能很好地与循环引用一起使用,因此我试图自己实现树形数据结构(但是借位检查器不允许我也可以这样做):

playground

struct Node {
    children: Vec<i32>,
}

let mut hm = HashMap::new();

hm.insert(1, Node { children: vec![] });
hm.insert(2, Node { children: vec![1] });

// Let's say I want to remove node 2...
let node = match hm.get(&2) {
    Some(node) => node,
    None => panic!(""),
};

// ...but first I want to remove its children:
for removable in &node.children {
    match hm.get(&removable) {
        Some(_) => hm.remove(&removable), // cannot borrow `hm` as mutable because it is also borrowed as immutable
        None => panic!("Oops, trying to remove data that's not there"),
    };
}

如何解决?

0 个答案:

没有答案