这是我的代码,下面是编译器错误。
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()
是不可变的借项?
我只是想退还布尔值,似乎我没有借任何东西。要成功编译程序,我需要进行哪些更改?
答案 0 :(得分:0)
您可以尝试以下方法:
fn main() {
let mut s = String::new();
let mut push_if = |b, some_str, string: &mut String| {
if b {
string.push_str(some_str);
}
};
push_if(s.is_empty(), "Foo", &mut s);
println!("{}", s);
}