The `&mut list` been released or not

struct Manager<'a> {
    text: &'a str,
}

struct List<'a> {
    manager: Manager<'a>,
}

impl<'a> List<'a> {
    pub fn xxx(self: &'a mut List<'a>) {}

    pub fn yyy<'b>(self: &'b mut List<'a>) {}
}

fn main() {
    let mut list = List {
        manager: Manager { text: "hello" }
    };
    list.xxx();			// Produced one &'a mut list<'a >
    list.text = 20;		// error
}

This code produce a permanent borrow &'a mut List<'a>, and the list can no longer be accessed.
My question is: does this mutable borrow &'a mut List<'a> actually last as long as the lifetime of list, or has this mutable borrow &'a mut List<'a> already been released, but the borrow checker notices that the lifetime annotation of the mutable borrow is the same as 'a, so the borrow checker rejects the code?

Yes

The borrow checker does not reason this way. It uses lifetime annotations to create constraints for the actual lifetimes, and then solve them. Types like &'a mut List<'a> generate almost conflicting requirements, with the only solution being borrowing as long as it exists.

4 Likes

Thank you once again for your answer

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.