不能作为不可变借用,因为它也作为可变借用

Cannot borrow as immutable because it also borrowed as mutable

我有以下最小示例来重现此问题:

fn main() {
    let mut vec = Vec::from(["Hello"]);
    let mut some_struct = SomeStruct { field: "World" };
    some_struct.doSomething(&mut vec);
    
    println!("{:?}", vec);
}

struct SomeStruct<'a> {
    field: &'a str
}

impl<'a> SomeStruct<'a> {
    fn doSomething(&mut self, vec: &'a mut Vec<&'a str>) {
        vec.push(self.field);
    }
}

(显然,doSomething 在这个例子中不需要对 self 进行可变引用,但我在原始代码中确实需要一个可变引用)

当我运行上面的例子时,我得到以下错误:

error[E0502]: cannot borrow `vec` as immutable because it is also borrowed as mutable
  --> src/main.rs:22:22
   |
20 |     some_struct.doSomething(&mut vec);
   |                             -------- mutable borrow occurs here
21 |
22 |     println!("{:?}", vec);
   |                      ^^^
   |                      |
   |                      immutable borrow occurs here
   |                      mutable borrow later used here
   |
   = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)

vecdoSomething可变借用后如何打印出来?

我试过克隆 vecRefCell,但似乎没有任何效果。

问题是&'a mut Vec<...>。重复一生通常是错误的。在这种情况下,您告诉 Rust “我想为 'a 借用 vec”。但是'a是由self.field决定的,在这里推断为'static(或者不是;其实并不重要,最重要的是它被推断为longer/equal 到 self 的生命周期,因为否则 self 将持有悬空引用)。现在,通过为 'a 借用 vec,您可以至少在 self 被销毁之前阻止使用它。

如果从 vec 中删除 'a 生命周期,it works:

fn doSomething(&mut self, vec: &mut Vec<&'a str>) {
    vec.push(self.field);
}