如何从闭包内部修改在闭包外部定义的变量?
Code:
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 多个具有相同错误消息的其他问题 https://stackoverflow.com/search?q=%5Brust%5D+cannot+borrow+as+immutable+because+it+is+also+borrowed+as+mutable+is%3Aq有关该错误的更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)