How to model complex recursive data structures (graphs)?

You can’t represent an arbitrary graph structure in safe rust.

The best way to implement this pattern is to use unsafe code and raw pointers, or an existing abstraction that wraps this functionality in a safe api, for example http://static.rust-lang.org/doc/master/std/cell/struct.RefCell.html

For example, the typical bi directional linked list would be:

struct Node {
  next: Option<Node>, // Each node 'owns' the next one
  prev: *mut Node     // Backrefs are unsafe
}

There have been a number of ‘safe’ implementations floating around, where you have something like:

struct Node {
    id: u32,
    next: u32,
    prev: u32
}
struct Nodes {
  all:Vec<Node>,
  root:Option<Node>
}

This is ‘technically’ safe, but it’s a terrible pattern; it breaks all the safety rules by just manually implementing raw pointers. I strongly advise against it.

You could try using references, eg:

struct Container<'a> {
  edges:Vec<Edge<'a>>,
  pub root: Node
}

struct Node {
  children:Vec<Node>  
}

struct Edge<'a> {
  n1: &'a Node,
  n2: &'a Node
}

…but you’ll stumble almost immediately into borrow checker hell. For example, when you remove a node, how does the borrow checker know that the associated links in ‘edges’ are no longer valid?

Although you might be able to define the structures, populating them will be extremely troublesome.

I know that’s probably a quite unsatisfying answer; you may find it useful to search github for ‘rust graph’ and ‘rust tree’ and look at the implementations other people have done.

Typically they enforce single-ownership of a sub-tree to a parent object.

Leave a Comment