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

前端 未结 2 1361
耶瑟儿~
耶瑟儿~ 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

    Consider this :

    struct Foo<'a> {
        x: &'a i32,
    }
    

    As the book states:

    So why do we need a lifetime here? We need to ensure that any reference to a Foo cannot outlive the reference to an i32 it contains.

    If you write something like:

    impl<'a> Graph<'a> {
        pub fn add_node(&'a mut self, data: (u64, u64)) -> usize {
            ...
    

    the lifetime declaration &'a mut self is not for the purpose of relating the lifetime of Graph instance with the contained references, but for declaring that for mutable self references hold the same lifetime 'a declared for Graph field references:

    fn main() {    
        let mut g = Graph {                          // <------------
            nodePointer: &mut 0,                     //             |            
            edgePointer: &mut 0,                     // lifetime    |
            nodes: &mut Vec::new(),                  // of Graph    | 'a
            edges: &mut Vec::new(),                  // references  |
        };                                           //             |
        let node1 = Graph::add_node(&mut g, (1, 1)); //             |   
        let node2 = Graph::get_node(&mut g, 0);      //             |
    }                                                //<-------------
    

    Where g.get_node(0) has been rewritten as Graph::get_node(&mut g, 0) just for explicitly exposing the &mut reference

    Looking at the lifetime of 'a it is clear that the reference &mut g is borrowed mutably more than once, and this causes the error.

提交回复
热议问题