:nerd_face: Closure can borrow automatically a variable
:bulb: Borrowing can be of below categories:
by value T
by ref i.e. &T
by mutable ref i.e. &mut T
:nerd_face: Automatic borrowing i.e. capturing understand what extent to borrow
:nerd_face: If only borrow by reference is required it will not borrow by mutable reference
fn main() {
use std::mem;
let color = "green";
// A closure to print `color` which immediately borrows (`&`)
// `color` and stores the borrow and closure in the `print`
// variable. It will remain borrowed until `print` goes out of
// scope. `println!` only requires `by reference` so it doesn't
// impose anything more restrictive.
let print = || println!("`color`: {}", color);
// Call the closure using the borrow.
print();
print();
:confounded: Ever heard of mutable closure?
:nerd_face: It is not just variables but closures which can be assigned with mut reference
:nerd_face: Keep a close eye on whether the closure stores any variable(s)
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.
//
// So count is borrowed as `&mut`
//
// A `mut` is required on `inc` as well because a `&mut` is stored inside.
// Thus, calling the closure mutates the closure which requires
// a `mut`.
let inc = || {
count += 1;
println!("`count`: {}", count);
};
// Call the closure.
inc();
inc();
:nerd_face: Closure can borrow automatically a variable :bulb: Borrowing can be of below categories:
T
&T
&mut T
:nerd_face: Automatic borrowing i.e. capturing understand what extent to borrow :nerd_face: If only borrow by reference is required it will not borrow by mutable reference
:confounded: Ever heard of mutable closure? :nerd_face: It is not just variables but closures which can be assigned with
mut
reference :nerd_face: Keep a close eye on whether the closure stores any variable(s)