【问题标题】:Cannot borrow X as immutable because it is also borrowed as mutable in a mutable closure不能将 X 作为不可变借用,因为它在可变闭包中也作为可变借用
【发布时间】: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() 是不可变的借用? 我只是想返回一个布尔值,这看起来不像我在借任何东西。我需要进行哪些更改才能成功编译程序?

【问题讨论】:

标签: rust


【解决方案1】:

你可以试试这个:

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

【讨论】:

  • 你能解释一下你是如何解决这个问题的,即你在这里做什么?
猜你喜欢
  • 2016-07-30
  • 2015-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
相关资源
最近更新 更多