如何从闭包内部修改在闭包外部定义的变量?
代码:
fn main() {
let mut t = "foo".to_string();
println!("{}", t);
let mut closure = | | {
t.clear();
};
closure();
println!("{}", t);
}
编译错误:
cannot borrow `t` as immutable because it is also borrowed as mutable [--explain E0502]
最佳答案
和你做的一样;那不是这里的问题。完整的错误消息显示了更多详细信息:
error: cannot borrow `t` as immutable because it is also borrowed as mutable [--explain E0502]
|> let mut closure = || {
|> -- mutable borrow occurs here
|> t.clear();
|> - previous borrow occurs due to use of `t` in closure
...
|> println!("{}", t);
|> ^ immutable borrow occurs here
|> }
|> - mutable borrow ends here
您已将变量的可变引用提供给闭包,并且闭包仍在范围内。这意味着它保留了引用,并且您无法拥有对该变量的任何其他引用。这显示了同样的问题:
fn main() {
let mut t = "foo".to_string();
println!("> {}", t);
let not_a_closure = &mut t;
println!("> {}", t);
}
在较小范围内创建闭包会强制闭包超出范围并在调用 println!
之前释放引用:
fn main() {
let mut t = "foo".to_string();
println!("> {}", t);
{
let mut closure = || {
t.clear();
};
closure();
}
println!("> {}", t);
}
我建议查看 60+ other questions with the same error message有关该错误的更多信息。
关于rust - 如何从闭包内部修改在闭包外部定义的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38423607/