自从今天升级到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中起了作用。还有办法让这件事在某种程度上发挥作用吗?
注意:我认为夜间构建和0.10构建是一个和相同的今天(4月3日),但我已经测试了这两个。同样的结果。
发布于 2014-04-04 03:38:25
在Rust 0.9中有效吗?我想这是修复这个循环的不稳定bug之一。
该代码确实需要多个可变借用,因此0.9行为是不正确的;0.10行为是正确的。
你可以做两件事:
RefCell<T>而不是T,来使用运行时的借用检查。Cell<T>而不是T,维护对象的本地副本而不是借用。https://stackoverflow.com/questions/22852174
复制相似问题