Cannot borrow variable as mutable more than once at a time after calling a &'a mut self method

前端 未结 2 1366
耶瑟儿~
耶瑟儿~ 2021-01-22 01:46

I have a problem with lifetimes/borrowing with my Graph object.

fn main() {
    let mut g = Graph {
        nodePointer: &mut 0,
        edgePoi         


        
2条回答
  •  执念已碎
    2021-01-22 02:33

    Your problem arises from a misuse of lifetimes, specifically in your signature of add_node:

    pub fn add_node(&'a mut self, data: (u64, u64)) -> usize
    

    In this signature, you are stating that add_node takes an &'a mut self on a Graph<'a>; in other words, you are telling Rust that this method needs to take a mutable borrow on the graph that can't be dropped before the end of the Graph's lifetime, 'a. But since it's the graph itself holding a reference to the graph, the only time that reference will be dropped is when the graph itself is dropped.

    Since add_node doesn't require you to return a reference to any object within the struct, holding onto that borrow is irrelevant. If you alter your add_node method to remove the explicit lifetime:

    pub fn add_node(&mut self, data: (u64, u64)) -> usize
    

    then your example no longer raises an error, because add_node is now only borrowing self until it's finished with the function. (Under the hood, this effectively creates a second lifetime 'b and makes the signature into &'b mut self)

    See the playground for proof.

提交回复
热议问题