我正在尝试创建一个包含可变引用的结构。通过其字段多次访问可变引用工作正常。但是,如果我改为使用getter,它就不会编译。
struct IntBorrower<'inner>(&'inner mut i32);
impl<'outer: 'inner, 'inner> IntBorrower<'inner> {
fn int_mut(&'outer mut self) -> &'inner mut i32 {
&mut self.0
}
//this compiles
fn do_something(&'outer mut self) {
{
*self.0 += 5;
}
{
*self.0 += 5;
}
}
//this does not compile
fn do_something_but_with_getters(&'outer mut self) {
{
*self.int_mut() += 5;
}
{
*self.int_mut() += 5;
}
}
}
fn main() {}
我收到此错误:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:26:14
|
22 | *self.int_mut() += 5;
| ---- first mutable borrow occurs here
...
26 | *self.int_mut() += 5;
| ^^^^ second mutable borrow occurs here
27 | }
28 | }
| - first borrow ends here
这些括号内的第一个可变借位是否应该像上一个函数一样?为什么会这样?