Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...