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?