可变借入循环 [英] Mutable borrow in loop

查看:145
本文介绍了可变借入循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个循环中获得一个可变的借项,但我无法使其正常工作.我已经尝试了所有可能的防护措施,原始指针等等.

I am trying to get a mutable borrow inside a loop, and I cannot get it to work. I've tried all the possible guards, raw pointers, everything.

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示例代码

我无法弄清楚如何解决这个问题.我需要修复以使功能签名保持不变.我的代码要复杂得多,但是此代码片段将其缩减到最低限度.

I cannot manage to figure how to solve this. I need the fix to still keep the function signatures the same. My code is a lot more complex, but this snippet strips it down to the bare minimum.

这是我所用代码的完整代码试图解决.

推荐答案

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

When you write fn dostuff(&'a mut self) you are enforcing that the reference to self must live at least as long as the lifetime 'a. But it's the same 'a as you have used in the definition of the Test struct. This means that callers of dostuff have to lend self for the entire lifetime of test. After dostuff() has been called once, self is now borrowed and the borrow doesn't finish until test is dropped. By definition, you can only call that function once, so you cannot call it in a loop.

我需要修复程序以使功能签名保持不变

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

因此,您现在应该了解这是不可能的要求.您既可以直接使用函数签名,也可以循环调用它.不能同时拥有.

So, you should now understand that this is an impossible requirement. You can have either the function signature as it is, or you can call it in a loop. You can't have both.

这篇关于可变借入循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆