【发布时间】:2018-10-03 19:59:11
【问题描述】:
fn main() {
let mut a = String::from("a");
let closure = || {
a.push_str("b");
};
closure();
}
这不会编译:
error[E0596]: cannot borrow immutable local variable `closure` as mutable
--> src/main.rs:7:5
|
3 | let closure = || {
| ------- consider changing this to `mut closure`
...
7 | closure();
| ^^^^^^^ cannot borrow mutably
如果我在闭包中返回a而不添加mut,则可以编译:
fn main() {
let mut a = String::from("a");
let closure = || {
a.push_str("b");
a
};
closure();
}
这让我很困惑。似乎当我调用closure() 时,closure 将被借用,如果其中的某些内容是可变的。为什么我回a时不借?
【问题讨论】:
标签: rust