【发布时间】:2016-02-20 14:19:03
【问题描述】:
我正在尝试构建一个自我引用的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 }
^
【问题讨论】:
-
请edit 解释为什么它不是many questions with the same error message 之一的重复项。否则,我们可能会重复以前的答案,从而使人们更难寻找解决方案,并且不会告诉您任何新内容!
标签: hashmap rust borrow-checker