为什么我不能多次调用变异函数?

Why can't I call a mutating function more than once?

这是基于我之前的question

我的代码因借用检查器错误而失败,我尽可能地减少了它。这是结果:

struct MyStruct<'a> {
    s: &'a str,
}

impl<'a> MyStruct<'a> {
    fn foo(&'a mut self) {}
}

fn main() {
    let mut m = MyStruct { s: "aaa" };

    m.foo();
    m.foo();
}

它失败了:

error[E0499]: cannot borrow `m` as mutable more than once at a time
  --> src/main-x.rs:13:5
   |
12 |     m.foo();
   |     - first mutable borrow occurs here
13 |     m.foo();
   |     ^
   |     |
   |     second mutable borrow occurs here
   |     first borrow later used here

代码被精简到没有任何用处,可以修复,例如从 foo 函数中删除 'a 生命周期。但我想了解为什么代码不正常。

我的理解是 MyStruct 包含对某个生命周期 'astr 的引用,并且 foo 可以通过 self 指向 [=14] 来调用=] 相同的生命周期。我不明白为什么 m 在第一次调用 foo 后被认为是可变借用的。

当您将 foo 声明为

 fn foo(&'a mut self) {}

你说 self 的可变借用与嵌入字符串具有相同的生命周期 'a。所以只要结构存在,它就会一直被借用。调用 foo 就像绝对放弃结构的所有权。

您可以通过将 foo 声明为

来修复它
 fn foo(&mut self) {}