rust - 不能借用 X 作为不可变的,因为它在可变闭包中也被借用为可变的

标签 rust

这是我的代码,下面是编译器错误。

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() 是不可变的借用? 我只是想返回一个 bool 值,这看起来不像是我在借用任何东西。我需要做哪些更改才能成功编译程序?

最佳答案

你可以试试这个:

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);
}

关于rust - 不能借用 X 作为不可变的,因为它在可变闭包中也被借用为可变的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58721780/

相关文章:

datetime - 如何找到 2 个 NaiveDateTimes 之间的区别?

rust - 为什么不能在同一结构中存储值和对该值的引用?

rust - 如何创建一个特征来指定超特征的关联类型?

arrays - 比较定长数组

asynchronous - 如何实现轮询异步 fn 的 Future 或 Stream?

rust - 逐字包装辅助函数中的代码会导致借入错误

loops - 具有生命周期界限的递归函数内循环中的借用检查器错误

rust - 使用 Rust bindgen 链接头文件的问题

rust - Rust 的借用检查器在这里真正提示的是什么?

json - 尝试从标准输入读取 JSON 时出现借用错误