Why is dereferencing not required inside a closure when auto captured by mutable reference?

Capturing - Rust By Example (rust-lang.org) line 26 - 36.

let mut x = 13;

let y: &mut i32 = &mut x;
*y = *y + 1; // Expected to be this.

let mut fun = || { // Auto capture by `&mut x`.
    x = x + 1; // Why not `*x = *x + 1;`?.
};
fun();

Is it getting automatically derefenced, just like in calling methods on references?

x is i32, how can it be dereferenced? I don't know.

This description

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`.
let mut inc = || {
        count += 1;
        println!("`count`: {}", count);
    };

I know count can be accessed directly inside the closure, but why &mut count and borrowing?

This is because if a move is possible, then any type of borrow should also be possible. Note that the reverse is not true. If the parameter is annotated as Fn, then capturing variables by &mut T or T are not allowed. However, &T is allowed.

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.