I am trying to implement a graph structure by having each node store references to its neighbors. Specifically, I am trying to make a grid where each node has references to up to 4 neighbors - like a "2D linked list".
But I get an error when assigning the references. This minimalistic example reproduces my issue:
#[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]);
}
The following error is produced:
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`.
I am struggling to figure out how this is supposed to be done in Rust. Should I be using pointers instead?