Closures Capturing

    let mut count = 0;
    // A closure to increment `count` could take either `&mut count` or `count`
    // but `&mut count` is less restrictive so it takes that. Immediately
    // borrows `count`.
    // A `mut` is required on `inc` because a `&mut` is stored inside. Thus,
    // calling the closure mutates the closure which requires a `mut`.
    let mut inc = || {
        count += 1;
        println!("`count`: {}", count);

The documentation states that the &mut variable that stores the count in the closure, but shouldn't the count here be itself? Or is the c-operation bbf of += essentially an operation via &mut count? Or is it &mut count in the closure that is dereferenced when the function is executed, *&mut count+=1?

+= needs &mut, and the println! only needs & access, so the closure as a whole needs &mut.

If you instead declared the closure as move, that is let mut inc = move || {, then count would be moved (copied) into the closure instead. move changes the capture policy from “take the weakest access necessary” to “always move”. (Note that this would mean, possibly surprisingly, that code using count after the closure is no longer in use would not see the new value, because the closure has its own copy instead of mutating the original count variable.)

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.