Container does not live enough


#1
struct Node<'a> {
    subnodes: Vec<&'a mut Node<'a>>,
}

impl<'a> Node<'a> {
    fn add_node(&'a mut self, node: &'a mut Node<'a>) {
        self.subnodes.push(node);
    }
}

fn main() {
    {
        let mut slave = Node { subnodes: Vec::new() };
        let mut master = Node { subnodes: Vec::new() };
        master.add_node(&mut slave);
    }
    println!("Hello, world!");
}

It shows error that master does not live enough.


#2

This should be just &mut self, not using 'a. When you plug in 'a on self here, it requires that the borrow of self (just to call the method add_node and return again), needs to be just as long as the borrow of the Node reference that is passed in which is not correct.

With that said, further progress with this data structure will be tricky, since it’s self referencing using mutable references, which places very strict requirements on the references that are used – in fact every node you add to master will need to come from the same let binding.


#3

I don’t understand why. Could you please explain or give me a link to some explanation?


#4

The explanation comes from some dark magic known as Subtyping and Variance

In short, since mutable references represent read-writable data, they need exact type equality. The construction of the recursive data structure then implies that every Node<'a> needs to contain a mut reference with exactly the same lifetime, or scope, which is as detailed as the statement level in Rust.

(The exception is the top level, here master.)


#5

How Node must look to allow code

struct Entity {
    master: Node,
    slave: Node,
}

impl Entity {
    fn new() -> Entity {
        let mut entity = Entity { master: Node::new(), slave: Node::new() };
        entity.master.add_node(&mut slave);
        entity
    }
}