How do I express mutually recursive data structures in safe Rust?

Viewed 10163

I am trying to implement a scenegraph-like data structure in Rust. I would like an equivalent to this C++ code expressed in safe Rust:

struct Node
{
    Node* parent; // should be mutable, and nullable (no parent)
    std::vector<Node*> child;

    virtual ~Node() 
    { 
        for(auto it = child.begin(); it != child.end(); ++it)
        {
            delete *it;
        }
    }

    void addNode(Node* newNode)
    {
        if (newNode->parent)
        {
            newNode->parent.child.erase(newNode->parent.child.find(newNode));
        }
        newNode->parent = this;
        child.push_back(newNode);
    }
}

Properties I want:

  • the parent takes ownership of its children
  • the nodes are accessible from the outside via a reference of some kind
  • events that touch one Node can potentially mutate the whole tree
3 Answers
Related