0

I need to implement a tree-like data structure, in which each node possibly has 2 children, and each child node has a reference to its parent (except root node). Here is a sketch:

strcut Node {
    parent:  Option< ??? >,
    child_1: Option<Box<Node>>,
    child_2: Option<Box<Node>>
}

As you can see I don't know what type should a parent field be. Can it be just a plain unsafe pointer? What is the proper way of implementing it?

3
  • You can make do with Option<Rc<Node>> and Option<Weak<Node>>, but some operations are more easily and efficiently implemnted with some unsafe code. Commented Feb 14, 2023 at 9:07
  • @SvenMarnach Option<Weak> is unecessary; Weak can already be empty with Weak::new() (with what I consider to be a design mistake, but not it's too late to fix). Commented Feb 14, 2023 at 13:15
  • @ChayimFriedman Right, and you probably also need RefCell inside the Rc to be able to do anything useful. Commented Feb 14, 2023 at 15:53

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.