Search code examples
rustclosures

Question on borrowing in Rust with closures


I am trying a sample program in Rust to understand closures as follows. But I get in error for the line "After defining closure" below.

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

The error is as follows.

|
61 |     let mut borrows_mutably = || list.push(7);
|                               -- ---- first borrow occurs due to use of `list` in closure
|                               |
|                               mutable borrow occurs here
62 |     println!("After defining closure: {list:?}");
|                                       ^^^^^^^^ immutable borrow occurs here
63 |
64 |     borrows_mutably();
|     --------------- mutable borrow later used here

My question is why does the first borrow happen when I defined the closure. Shouldn't it be after I call the closure?


Solution

  • I figured out the following explanation from the Rust book. Looks like the definition of closure itself is doing the borrow, though I can't understand the rationale behind it.

    Between the closure definition and the closure call, an immutable borrow to print isn’t allowed because no other borrows are allowed when there’s a mutable borrow.