0

I have a tree-like data structure. Every Node may have two children (left and right). Also each node may have a parent node. I need to set a parent node inside method 'set_left'. How should I do this?

pub struct Node<'a> {
    parent: Option<&'a Node<'a>>,
    data: u32,
    pub left: Option<Box<Node<'a>>>,
    pub right: Option<Box<Node<'a>>>
}

impl<'a> Node<'a> {
    pub fn new(data: u32) -> Node<'a> {
        Node { 
            parent: None, 
            data,
            left: None,
            right: None,
        }
    }

    pub fn set_left(&mut self, child: Option<Box<Node<'a>>>) {
        self.left = child;
        match &self.left {
            // Errors here:
            Some(node) => { node.parent = Some(&self); } ???
            None => (),
        }
    }
}
  • 1
    It's not possible with references because `parent` contains `parent.left` which would need to store a reference to `parent` and [you can't store a value and a reference to that value in the same struct](https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct) – cafce25 Feb 17 '23 at 12:48
  • @cafce25 Even if it answers, I still don't know how to apply this answer to my question with my knowledge. That's why I'm asking. – Евгений Павлов Feb 17 '23 at 12:51
  • @cafce25 It's not storing value an a reference to that value, it's storing value and a reference to another value of the same type. – Евгений Павлов Feb 17 '23 at 12:55
  • `node.left.parent == &node` though so it's storing a reference to `node` in `node`, the answers of the linked question have several solutions how to overcome this. – cafce25 Feb 17 '23 at 12:58
  • 1
    Before attempting to implement a tree structure in Rust, please read through [this book](https://rust-unofficial.github.io/too-many-lists/) to understand how the borrow checker interacts with linked lists. It will save you *a lot* of frustration. – user4815162342 Feb 17 '23 at 13:16

0 Answers0