Hey can you help me

I do not understand what is explained in the book, why does it give an error in this line?
Is it because it's a mutable reference? can you tell me in detail

    let mut list = vec![1, 2, 3];
    println!("Before defining closure: {:?}", list);
    
    let mut borrows_mutably = || list.push(7);    
    borrows_mutably();
    println!("After calling closure: {:?}", list);
    borrows_mutably();

Yes, it's because of the mutable reference. One of the defining features of mutable references in Rust is exclusivity: While a mutable reference to list¹ exists, nothing else is allowed to use or read list in any way. This way, code that holds a mutable reference can be sure that any temporary changes it makes won't be seen by the outside world, and it only needs to ensure that it leaves list in a valid state when it gives up the reference.

¹ Or anything else, for that matter.

5 Likes

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.