when &'a self bind a LifeTime , not support mutable more than once at a time!

It should be able to be modified twice。Because they all use the same of LifeTime.

pub struct NumberList<'a> {
    pub vec: Vec<&'a mut i32>,
    pub self_number: i32,
}

impl<'a> NumberList<'a>{
    pub fn push_self_number(&'a mut self) {
        self.vec.push(self.self_number.borrow_mut());
    }
}

#[test]
pub fn test() {
    let mut n = NumberList {
        vec: vec![],
        self_number: 0,
    };
    {
        n.push_self_number();
    }
    n.push_self_number();
}
//run test() result =>>>   
error[E0499]: cannot borrow `n` as mutable more than once at a time
   --> src\local_session.rs:298:5
    |
296 |         n.push_self();
    |         - first mutable borrow occurs here
297 |     }
298 |     n.push_self();
    |     ^
    |     |
    |     second mutable borrow occurs here
    |     first borrow later used here

if you remove the LifeTime 'a

impl<'a> NumberList<'a>{
    pub fn push_self_number(&mut self) {
        self.vec.push(self.self_number.borrow_mut());
    }
}
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
   --> src\local_session.rs:285:40
    |
285 |         self.vec.push(self.self_number.borrow_mut());
    |                                        ^^^^^^^^^^

You're trying to create a self-referential struct with multiple mutable borrows of itself. That's disallowed in all manner of ways.

You should be aware that push_self_number(&mut self) takes a unique borrow of self, i.e., the entire struct. Thus you can't modify the vec when you've already got a unique reference to it. The rust ownership model also requires that types generally be relocatable in memory, and any struct with self-borrows cannot be moved without being invalidated, so it isn't so easy to construct such a thing.

It is best to think of &mut as offering you mutually exclusive access to data, not merely allowing mutation of it.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.