我有以下代码:
struct Baz {
x: usize,
y: usize,
}
struct Bar {
baz: Baz,
}
impl Bar {
fn get_baz_mut(&mut self) -> &mut Baz {
&mut self.baz
}
}
struct Foo {
bar: Bar,
}
impl Foo {
fn foo(&mut self) -> Option<&mut Baz> {
for i in 0..4 {
let baz = self.bar.get_baz_mut();
if baz.x == 0 {
return Some(baz);
}
}
None
}
}
编译失败,错误信息如下:
error[E0499]: cannot borrow `self.bar` as mutable more than once at a time
--> src/main.rs:23:23
|
23 | let baz = self.bar.get_baz_mut();
| ^^^^^^^^ mutable borrow starts here in previous iteration of loop
...
29 | }
| - mutable borrow ends here
然而,如果我从
Foo::foo
返回Some(baz.x)
(并将返回类型更改为Option<usize>
),则代码编译。这使我相信问题不在于循环,尽管编译器似乎表明如此。更具体地说,我认为局部可变引用baz
将在下一次循环迭代时超出范围,导致这不是问题。上述代码的生命周期问题是什么?以下问题类似: 然而,它们处理明确声明的生命周期(特别是这些明确的生命周期是答案的一部分)。我的代码省略了这些生命周期,因此删除它们并不是一个解决方案。