我试图在循环内获取可变借用,但无法使其正常工作。我尝试了所有可能的保护机制、原始指针和其他所有方法。
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
我无法弄清楚如何解决这个问题。 我需要修复程序并仍保持函数签名不变。 我的代码更加复杂,但是这段代码将其简化到最少。
这里是我正在尝试解决的完整代码。
&str
而不是String
的充分理由吗?如果Test
拥有该字符串,请使用拥有所有权的类型。 - Boiethios