我正在尝试建立一个自我参照HashMap
:
use std::collections::HashMap;
struct Node<'a> {
byte: u8,
map: HashMap<i32, &'a Node<'a>>,
}
fn main() {
let mut network = HashMap::<u32, Node>::new();
network.insert(0, Node { byte: 0, map: HashMap::<i32, &Node>::new() });
network.insert(1, Node { byte: 1, map: HashMap::<i32, &Node>::new() });
let zeroeth_node = network.get(&0).unwrap();
let mut first_node = network.get_mut(&1).unwrap();
first_node.map.insert(-1, zeroeth_node);
}
我遇到了借用检查器错误,但我不明白它的来源——是我更新HashMap
错误的方法,还是我对它的自我引用使用?
错误:
<anon>:15:26: 15:33 error: cannot borrow `network` as mutable because it is also borrowed as immutable [E0502]
<anon>:15 let mut first_node = network.get_mut(&1).unwrap();
^~~~~~~
<anon>:14:24: 14:31 note: previous borrow of `network` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `network` until the borrow ends
<anon>:14 let zeroeth_node = network.get(&0).unwrap();
^~~~~~~
<anon>:18:2: 18:2 note: previous borrow ends here
<anon>:8 fn main() {
...
<anon>:18 }
^