我正在尝试通过让每个节点存储对其邻居的引用来实现图形结构。具体而言,我正在尝试创建一个网格,其中每个节点都有对高达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中应该如何完成这项任务。我应该使用指针吗?
Rc
。 - Netwave