user2618270
user2618270

Reputation: 11

Rust Closures concept

I am unable to understand this concept here about Rust closures. As in my code count is default i32. When I create mutable closure then it will take mutable reference of variable used in it as mentioned in documentation.

When I call inc closure in loop and try to print value of count inside loop I will get mutable borrow used error but if I print value of count outside of the loop it’s fine. Even in loop when I call inc() closure before print macro inc() goes out of scope then why it provoke error.

fn main() {
    let mut count = 0;

    let mut inc = || {
        count += 2;
    };

    for _index in 1..5 {
        inc();
        println!("{}", count);
    }
}

Upvotes: 1

Views: 290

Answers (1)

Jmb
Jmb

Reputation: 23463

When you create the closure, it borrows mutably the count variable. It is forbidden to access the count variable through another reference while the mutable borrow is alive (including the count variable itself). The closure is dropped when it is no longer used, at which point it releases the borrow which makes it possible to access count again.

fn main() {
    let mut count = 0;

    let mut inc = || {
        count +=2;
    };
    // Now we can't access `count`

    for _index in 1..5 {
        inc();
        // println!("{}", count);
        // Here we can't access `count` because it is borrowed mutably by `inc`
    }
    // Here `inc` is dropped so `count` becomes accessible again
    println!("{}", count);
}

Upvotes: 1

Related Questions