循环中的可变借用

Mutable borrow in loop

我试图在循环中获取可变借用,但我无法让它工作。我已经尝试了所有可能的守卫,原始指针,一切。

struct Test<'a> {
    a: &'a str,
}

impl<'a> Test<'a> {
    pub fn new() -> Self {
        Test { a: &mut "test" }
    }

    pub fn dostuff(&'a mut self) {
        self.a = "test";
    }

    pub fn fixme(&'a mut self) {
        let mut i = 0;
        while i < 10 {
            self.dostuff();
            i += 1;
        }
    }
}

fn main() {
    let mut test = Test::new();
    test.fixme();
}
error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> src/main.rs:19:13
   |
19 |             self.dostuff();
   |             ^^^^ mutable borrow starts here in previous iteration of loop
...
22 |     }
   |     - mutable borrow ends here

Rust Playground example code

我想不出如何解决这个问题。我需要修复以保持函数签名不变。我的代码要复杂得多,但这段代码将它精简到最低限度。

这里是the complete code of what I'm trying to solve

当您写 fn dostuff(&'a mut self) 时,您是在强制对 self 的引用必须至少与生命周期 'a 一样长。但它与您在 Test 结构的定义中使用的 'a 相同。这意味着 dostuff 的调用者必须在 test 的整个生命周期内借出 self。在 dostuff() 被调用一次后,现在 self 被借用并且借用直到 test 被删除才完成。根据定义,您只能调用该函数一次,因此不能在循环中调用它。

I need the fix to still keep the function signatures the same

所以,你现在应该明白这是一个不可能的要求了。您可以按原样使用函数签名,也可以在循环中调用它。你不能两者兼得。