在下面的代码中,我明确强制将来自
相反,我却收到了错误信息:
main
函数的name
移入闭包中,一切都可以正常运行:fn main() {
let name = String::from("Alice");
let welcome = || {
let mut name = name;
name += " and Bob";
println!("Welcome, {}", name);
};
welcome();
}
我原本认为在闭包的开头添加move
就可以达到同样的效果,从而移动值并创建一个FnOnce
:
fn main() {
let name = String::from("Alice");
let welcome = move || {
name += " and Bob";
println!("Welcome, {}", name);
};
welcome();
}
相反,我却收到了错误信息:
error[E0596]: cannot borrow immutable local variable `welcome` as mutable
--> main.rs:9:5
|
4 | let welcome = move || {
| ------- help: make this binding mutable: `mut welcome`
...
9 | welcome();
| ^^^^^^^ cannot borrow mutably
error[E0596]: cannot borrow captured outer variable in an `FnMut` closure as mutable
--> main.rs:5:9
|
5 | name += " and Bob";
| ^^^^
在这种情况下,如何正确思考闭包中的move
?
help: make this binding mutable: \
mut welcome`` - Shepmaster