我試圖在循環中獲得可變借入,並且我無法使其工作。我已經嘗試了所有可能的衛兵,生魚指針,一切。循環中的可變借用
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
我不能設法弄清楚如何解決這個問題。我需要修復仍然保持功能簽名相同。我的代碼更加複雜,但是這個代碼片段將其剝離到最低限度。
這裏是the complete code of what I'm trying to solve。
*我需要的修復仍然保持相同的功能* - 如果我們不能改變任何東西,我們不能修復任何東西。 – Shepmaster
你有充分的理由使用'&str'而不是'String'嗎?如果'Test'擁有該字符串,則使用擁有的類型。 – Boiethios
我已經添加了我遇到的實際代碼。推到一個git回購。操場的要點只是錯誤本身的一個例子。 – Chronium