How would I return a borrowed variable?
I'm trying to make a simple function with 2 statements both of which mutate 2 variables to link them together
impl<'a> Node<'a> {
// Add a child to this node
pub fn add_child(&'a mut self, child: &'a mut Node<'a>) {
self.children.push(child); // Add child to Vec<&'a Node<'a>>
child.parent = Some(self); // Set child's parent to Option<&'a Node<'a>>
}
}
What I understand is that a reference to child is pushed onto self.children at line 4, and there can be any number of references because it is an immutable reference.
Then child is mutably borrowed at line 5 and its parent field is assigned a value, but the rust compiler gives an error saying that I can't assign to child.parent because it's borrowed at line 4.
Is there any way to drop the borrow after line 4 or do I need to restructure the function?
Posted Jun 25, 2021, 10:02 AM UTC
There's a fundamental problem with what you're trying to do, which is trying to create a self referential struct, which is not possible in safe rust. If this was possible then
node.children[0].parent.unwrap()would get you a shared borrow ofnodewhile also leaving the rest ofnodenot borrowed; this way you can have a mutable reference and a shared reference to the same data at the same time, and this is UB.A big red flag for this cases should be the
&'a mut self. You almost never want a&'a mut Node<'a>. This is saying that aNode<'a>can't live more than'abecause otherwise the references it contains would become invalid, but at the same time you want a reference to it that last at least'a. This is a contradiction, and even if it compiles it would be unusable (usually you either get an error when you call that function or you can't touch the struct anymore after calling it).If you're trying to create some sort of tree/graph I would suggest you to store the nodes in a vec and use indexes instead of pointers to point to the parent/childrens. The petgraph crate also helps with this approach.
Ohh thank you that makes more sense, I'll try the last approach :p