I'm working with a struct Node and node_map defined as
pub struct Node<'a> {
id: i32,
next: HashMap<String, &'a Node<'a>>,
}
let mut node_map = HashMap::<i32, LexerNode>::new();
I'm using the node_map as shown below
let Some(node) = node_map.get_mut(&node_id) else {
return Err("Invalid node_id".to_string());
};
// some logic to get edge_pairs
for pair in edge_pairs {
// some logic to get neighbour_id
let Some(neighbour) = node_map.get(&neighbour_id) else {
return Err("Invalid node_id".to_string());
};
node.next.insert(char.to_string(), neighbour);
}
I'm getting the error
cannot borrow node_map as immutable because it is also borrowed as mutable
immutable borrow occurs here [E0502]
which refers to the node.next.insert statement. I need node to be mutable (to be able to insert the new value) and neighbour to be immutable. It's giving this borrowing error. How do I fix this? I would prefer not using a clone since I want a reference to the nodes.
Nodeto own its children (HashMap<String, Node>) you will make your life much easier.Vec<Node>and donext: HashMap<String, usize>. Adding a new node means appending to theVecand inserting(key, vec.len()-1)intonext. As long as you never delete a node from theVec, your indices will remain valid.