I am stuck in a situation where rusts "Safe nature" seems to be causing a problem. Below is a code snippet from a small program I am working on to practice lifetimes and borrowing references.
The code creates a vector of 10 node structs. Each node holds two pieces of information: it's index and a list of node references. The nodes are initialized to hold one node reference only; itself. It is entirely possible, however that a node can hold a reference to any other node in the mesh vector.
My issue occurs because in order to change a node it must be mutable. However because it is mutable I get an error due to the fact that a borrowed reference is mutable. does anybody know how I can solve this problem?
fn main() {
let mut mesh: Vec<Node> = vec![];
for i in 0..10 {
mesh.push(new_node(i));
}
for i in mesh.iter() {
println!(
"index: {}, connections: {}",
i.node_index,
i.node_connections.len()
);
}
}
fn new_node<'a>(index: i32) -> Node<'a> {
let mut node = Node {
node_connections: vec![],
node_index: index as u32,
};
node.node_connections.push(&node);
node
}
struct Node<'b> {
node_connections: Vec<&'b Node<'b>>,
node_index: u32,
}