0

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,
}
Kitsu
  • 3,166
  • 14
  • 28
  • 1
    You cannot accomplish this with references alone. You may want to look into using a [reference counted smart pointer (`Rc`)](https://doc.rust-lang.org/book/ch15-04-rc.html) for shared ownership of nodes and [interior mutability](https://doc.rust-lang.org/reference/interior-mutability.html) if you need to mutate shared notes. – Brian61354270 Jul 05 '20 at 20:18
  • 1
    I don't think this can be easily done, check out this article https://cfsamson.github.io/books-futures-explained/4_pin.html - for me it was quite helpful to understand why self referential structs are working like they do (esp. with stack allocations). – lpiepiora Jul 05 '20 at 20:19

0 Answers0