如何使用共享捕获变量的多个闭包编译Rust 0.10?

时间:2014-04-04 01:58:20

标签: rust

自从今天升级到Rust 0.10后,我发现此代码不再有效:

let mut outer_value = 0;

let add = |x| {
    outer_value += x;
};

let multiply = |x| {
    outer_value *= x;
};

//Showing commented code to demonstrate intent
//add(4);
//multiply(6);
//println!("{:d}", outer_value);

这给了我这些编译错误:

closures.rs:13:20: 15:6 error: cannot borrow `outer_value` as mutable more than once at a time
closures.rs:13     let multiply = |x| {
closures.rs:14         outer_value *= x;
closures.rs:15     };
closures.rs:14:9: 14:20 note: borrow occurs due to use of `outer_value` in closure
closures.rs:14         outer_value *= x;
                       ^~~~~~~~~~~
closures.rs:9:15: 11:6 note: previous borrow of `outer_value` occurs here due to use in closure; the mutable borrow prevents subsequent moves, borrows, or modification of `outer_value` until the borrow ends
closures.rs:9     let add = |x| {
closures.rs:10         outer_value += x;
closures.rs:11     };
closures.rs:22:2: 22:2 note: previous borrow ends here
closures.rs:6 fn main() {
...
closures.rs:22 }
               ^
error: aborting due to previous error

这适用于Rust 0.9。是否还有办法以某种方式使这项工作?

注意:我认为Nightly版本和0.10版本今天(4月3日)是同一个版本,但我已经对它们进行了测试。结果相同。

1 个答案:

答案 0 :(得分:2)

在Rust 0.9中有效吗?我想这是在这个循环中打补丁的一个不健全的错误。

该代码确实需要多次可变借用,因此0.9行为不正确; 0.10的行为是正确的。

您可以做两件事:

  • 重构您的代码,以便不需要此要求,或
  • 使用RefCell<T>代替T,以使用运行时借用检查。
  • 使用Cell<T>代替T,维护对象的本地副本而不是借用。