如何修改从闭包内部在闭包外定义的变量?

时间:2016-07-17 16:49:10

标签: rust

如何从闭包内部修改在闭包之外定义的变量?

代码:

fn main() {
    let mut t = "foo".to_string();
    println!("{}", t);

    let mut closure = | | {
        t.clear();
    };
    closure();

    println!("{}", t);
}

编译错误:

cannot borrow `t` as immutable because it is also borrowed as mutable [--explain E0502]

1 个答案:

答案 0 :(得分:2)

正如你所做的那样;这不是问题所在。完整的错误消息显示更多详细信息:

error: cannot borrow `t` as immutable because it is also borrowed as mutable [--explain E0502]
    |>         let mut closure = || {
    |>                           -- mutable borrow occurs here
    |>             t.clear();
    |>             - previous borrow occurs due to use of `t` in closure
...
    |>     println!("{}", t);
    |>                    ^ immutable borrow occurs here
    |> }
    |> - mutable borrow ends here

您已将变量的可变引用赋予闭包,并且闭包仍在范围内。这意味着它保留了引用,您无法对该变量进行任何其他引用。这显示了同样的问题:

fn main() {
    let mut t = "foo".to_string();
    println!("> {}", t);
    let not_a_closure = &mut t;
    println!("> {}", t);
}

在较小范围内创建闭包会强制闭包超出范围并在调用println!之前释放引用:

fn main() {
    let mut t = "foo".to_string();
    println!("> {}", t);

    {
        let mut closure = || {
            t.clear();
        };
        closure();
    }

    println!("> {}", t);
}

我建议查看60+ other questions with the same error message以获取有关错误的更多信息。