letmut num =5;let plus_num =|x:i32| x + num;let y =&mut num;
错误是:
error: cannot borrow `num` as mutable because it is also borrowed as immutable
let y = &mut num;
^~~
note: previous borrow of `num` occurs here due to use in closure; the immutable
borrow prevents subsequent moves or mutable borrows of `num` until the borrow
ends
let plus_num = |x| x + num;
^~~~~~~~~~~
note: previous borrow ends here
fn main() {
let mut num = 5;
let plus_num = |x| x + num;
let y = &mut num;
}
^
letmut num =5;{let plus_num =|x:i32| x + num;} // plus_num goes out of scope, borrow of num endslet y =&mut num;
如果你的闭包需要它,Rust会取得所有权并移动环境:
let nums =vec![1, 2, 3];let takes_nums =|| nums;println!("{:?}", nums);
这会给我们:
note: `nums` moved into closure environment here because it has type
`[closure(()) -> collections::vec::Vec<i32>]`, which is non-copyable
let takes_nums = || nums;
^~~~~~~