【问题标题】:Mutable borrow in loop [duplicate]循环中的可变借用[重复]
【发布时间】:2018-03-05 18:07:27
【问题描述】:

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

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

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

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

【问题讨论】:

  • 我需要修复以保持功能不变——如果我们不能改变任何东西,我们就不能修复任何东西。
  • 您是否有充分的理由使用&amp;str 而不是String?如果Test 拥有字符串,则使用拥有的类型。
  • 我已经添加了我遇到问题的实际代码。将其推送到 git repo。操场要点只是错误本身的一个示例。

标签: rust mutable borrow-checker


【解决方案1】:

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

我需要修复以保持函数签名不变

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

【讨论】:

  • 我有类似的问题,但我没有像 OP 那样严格的函数签名要求:我有什么选择?
猜你喜欢
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多