In the simple program:
struct Foo {
a: u32,
}
impl Foo {
fn f(&mut self) -> Option<&u32> {
for _ in 0..2 {
let x = &mut self.a;
if *x > 0 {
return Some(x);
}
}
None
}
}
fn main() {}
rustc 1.58.1 (db9d1b20b 2022-01-20) complained about a lifetime error:
error[E0499]: cannot borrow `self.a` as mutable more than once at a time
--> test2.rs:8:21
|
6 | fn f(&mut self) -> Option<&u32> {
| - let's call the lifetime of this reference `'1`
7 | for _ in 0..2 {
8 | let x = &mut self.a;
| ^^^^^^^^^^^ `self.a` was mutably borrowed here in the previous iteration of the loop
9 | if *x > 0 {
10 | return Some(x);
| ------- returning this value requires that `self.a` is borrowed for `'1`
I'm puzzled by the error because the borrow &mut self.a
ends at the end of each iteration of the for
loop. If I change the program slightly into the following, the error goes away.
struct Foo {
a: u32,
}
impl Foo {
fn f(&mut self) -> Option<&u32> {
for _ in 0..2 {
let x = &mut self.a;
if *x > 0 {
return Some(&mut self.a);
}
}
None
}
}
fn main() {}