AmitKumarDas / Decisions

Apache License 2.0
10 stars 3 forks source link

Rust: Closures can capture variables ~ i.e. auto borrow #134

Open AmitKumarDas opened 5 years ago

AmitKumarDas commented 5 years ago

:nerd_face: Closure can borrow automatically a variable :bulb: Borrowing can be of below categories:

: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();