自从今天升级到 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 build 和 0.10 build 在今天(4 月 3 日)是一样的,但我已经对两者进行了测试。相同的结果。
最佳答案
这在 Rust 0.9 中有效吗?我想这是本周期修补的不可靠错误之一。
该代码确实需要多次可变借用,因此 0.9 的行为不正确; 0.10 行为是正确的。
您可以做两件事:
- 重构你的代码,这样这个要求就没有必要了,或者
- 使用
RefCell<T>
而不是T
, 使用运行时借用检查。 - 使用
Cell<T>
而不是T
,维护对象的本地副本而不是借用。
关于rust - 如何使用共享捕获变量的多个闭包编译 Rust 0.10?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22852174/