0

I'm trying to represent a graph in Rust using the type:

struct Node<'a> {
    edges: Vec<&'a Node<'a>>,
}
type Graph<'a> = Vec<Node<'a>>;

A Graph has the constraint that all the nodes point at other nodes in the same vector. I can create a singleton graph:

fn createSingleton<'a>() -> Graph<'a> {
    let mut items: Graph<'a> = Vec::new();
    items.push(Node { edges: Vec::new() });
    return items;
}

But when I try and create a graph with two nodes, where one points at the other:

fn createLink<'a>() -> Graph<'a> {
    let mut items: Graph<'a> = Vec::new();
    items.push(Node { edges: Vec::new() });
    items.push(Node { edges: vec![&items[0]] });
    return items;
}

I get an error:

cannot borrow `items` as mutable because it is also borrowed as immutable

In particular the &items[0] is an immutable borrow, and the second items.push seems to be a mutable borrow. Is it possible to construct the memory layout I desire? If so, how?

Neil Mitchell
  • 9,090
  • 1
  • 27
  • 85

1 Answers1

1

As soon as more than one structure can point to one of your Nodes, you'll lose the "one owner" world of Rust's memory guarantees, and you'll either need something like an Rc, or more esoterically, a weakref. I totally suggest reading https://rust-unofficial.github.io/too-many-lists/ to learn the many ins and outs of this territory.

Dylan McNamee
  • 1,696
  • 14
  • 16