gpt4 book ai didi

rust - 如何从闭包内部修改在闭包外部定义的变量?

转载 作者:行者123 更新时间:2023-11-29 08:06:24 30 4
gpt4 key购买 nike

如何从闭包内部修改在闭包外部定义的变量?

代码:

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com