我试图在循环中获得可变借入,并且我无法使其工作。我已经尝试了所有可能的卫兵,生鱼指针,一切。循环中的可变借用
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