I'm implementing a basic data structure. I think I understand why the following code doesn't work: I can't mutably borrow and try to access (read) the value at the same time. However, I am stuck on how to implement add_ege
.
The whole idea is to have Graph
hold a list of Node
s in the heap. The Node
itself keeps track of adjacent nodes (edges). I don't want Node
to hold copies of Node
, I want it to have references to any of the Node
s held in Graph
.
struct Node<'a> {
value: String,
adj_nodes: Vec<&'a Node<'a>>, // refer to Graph.nodes
}
pub struct Graph<'a> {
nodes: Vec<Box<Node<'a>>>,
}
fn mk_node<'a>(value: String) -> Node<'a> {
Node {
value,
adj_nodes: vec![],
}
}
pub fn mk_graph<'a>() -> Graph<'a> {
let nodes = vec![];
Graph { nodes }
}
impl<'a> Graph<'a> {
fn add_node(&mut self, val: String) {
let node = Box::new(mk_node(val));
self.nodes.push(node);
}
fn add_edge(&mut self, from_node: &'a mut Node<'a>, to_node: &'a mut Node<'a>) {
from_node.adj_nodes.push(to_node);
// won't work because I already have from_node as mutable borrow
to_node.adj_nodes.push(from_node);
}
}
Is there a way to do this?