Trying to create a tree in rust with the following struct:
pub struct Node{
pub children: Vec<Box<Node>>,
pub parent: Option<Box<Node>>,
pub value: f32,
//.....
}
To build a new node the following function is used:
pub fn build_node(parent: Option<Box<Node>>)-> Node{
Node{
children: vec![],
parent,
value: 0.0,
}
}
When trying to add nodes, for example with:
let mut root_nd = tree::build_node(None, 5, state);
let mut next_nd = tree::build_node(Some(Box::new(root_nd)), 2);
root_nd.children.push(Box::new(next_nd));
There will be errors, because I am borrowing for example root_nd
and then trying to add next_nd
to the root.children
list, and even if there wasnt this error I would still need to have a reference for next_nd
after adding it to the children of root_nd
. I know that in rust it is not possible to have several mutable references simultaneously for the same element. So the question is how is it possible to make a tree-like data structure, with bi-directional references in rust? In my head this is a conflict since rust does not want multiple references but I need a node in the middle of the tree to be referenced by both his parent node and his children nodes.