首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用共享捕获变量的多个闭包编译Rust 0.10?

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

Stack Overflow用户
提问于 2014-04-04 01:58:20
回答 1查看 336关注 0票数 1

自从今天升级到Rust 0.10之后,我发现这段代码不再工作了:

代码语言:javascript
复制
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);

这给了我这些编译器错误:

代码语言:javascript
复制
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日),但我已经测试了这两个。同样的结果。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-04 03:38:25

在Rust 0.9中有效吗?我想这是修复这个循环的不稳定bug之一。

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

你可以做两件事:

  • 重构您的代码,以便不需要此要求,或
  • 使用RefCell<T>而不是T,来使用运行时的借用检查。
  • 使用Cell<T>而不是T,维护对象的本地副本而不是借用。
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22852174

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档