我试图通过让每个节点存储对其邻居的引用来实现图形结构。具体来说,我正在尝试制作一个网格,其中每个节点都引用了最多 4 个邻居——比如“二维链表”。
但是在分配引用时出现错误。这个简约的例子重现了我的问题:
#[derive(Clone)]
struct Node<'a> {
neighbor: Option<&'a Node<'a>>, // optional reference to another Node
}
fn main() {
// a bunch of nodes:
let mut nodes: Vec<Node> = vec![ Node{neighbor: None}; 100];
// I want node 0 to have a reference to node 1
nodes[0].neighbor = Some(&nodes[1]);
}
产生以下错误:
error[E0502]: cannot borrow `nodes` as mutable because it is also borrowed as immutable
--> src/main.rs:12:5
|
12 | nodes[0].neighbor = Some(&nodes[1]);
| ^^^^^------------------------------
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
| immutable borrow later used here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
我正在努力弄清楚这应该如何在 Rust 中完成。我应该改用指针吗?