【问题标题】:Rust Closures conceptRust 闭包概念
【发布时间】:2021-04-17 07:54:26
【问题描述】:

我无法理解这里关于 Rust 闭包的概念。正如我的代码计数默认为i32。当我创建可变闭包时,它将对其中使用的变量进行可变引用,如文档中所述。

当我在循环中调用 inc 闭包并尝试在循环内打印计数值时,我会得到可变借用错误,但如果我在循环外打印计数值,那就没问题了。即使在循环中,当我在打印宏 inc() 超出范围之前调用 inc() 闭包时,它为什么会引发错误。

fn main() {
    let mut count = 0;

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

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

【问题讨论】:

    标签: rust closures mutable ownership


    【解决方案1】:

    当您创建闭包时,它会可变地借用count 变量。当可变借用存在时(包括count 变量本身),禁止通过另一个引用访问count 变量。当不再使用闭包时,它会被丢弃,此时它会释放借用,从而可以再次访问count

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

    【讨论】:

    • 感谢您的回复@Jmb,我明白了。在声明为可变之后,我们无法在声明和闭包调用之间访问闭包中使用的变量。再澄清一下什么是关闭的生命周期?默认是静态的吗?
    • 不,它不是静态的。生命周期在它不能再被使用时结束(没有更多的代码路径导致使用它的语句)。在这种情况下,for 循环中的 inc 是最后一次使用,因此在 for 循环结束后,生命周期也结束,并且被丢弃。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多