【发布时间】:2019-11-06 01:22:06
【问题描述】:
这是我的代码,下面是编译器错误。
fn main() {
let mut s = String::new();
let mut push_if = |b, some_str| {
if b {
s.push_str(some_str);
}
};
push_if(s.is_empty(), "Foo");
println!("{}", s);
}
error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
--> src/main.rs:8:13
|
3 | let mut push_if = |b, some_str| {
| ------------- mutable borrow occurs here
4 | if b {
5 | s.push_str(some_str);
| - first borrow occurs due to use of `s` in closure
...
8 | push_if(s.is_empty(), "Foo");
| ------- ^ immutable borrow occurs here
| |
| mutable borrow later used by call
为什么编译器抱怨s.is_empty() 是不可变的借用?
我只是想返回一个布尔值,这看起来不像我在借任何东西。我需要进行哪些更改才能成功编译程序?
【问题讨论】:
-
看来Can't borrow mutably within two different closures in the same scope 的答案可能会回答您的问题。如果没有,请edit您的问题来解释差异。否则,我们可以将此问题标记为已回答。
-
我会看看那个答案然后回来。谢谢。
-
我查看了链接的问题 Shepmaster,并且对于像我这样的 Rust 新手,我发现很难理解,并且无法将来自该问题的见解应用于这个问题.我没有进一步理解为什么我的代码无法编译:(。
-
answer posted 是the first solution I linked 的一个应用程序('“将数据提升”到函数和闭包的参数')。
标签: rust