I have a segment of Rust code which, simplified, looks something like this:
struct FooRef<'f>(&'f mut i32);
fn blah<'f>(f: &'f mut i32) -> FooRef<'f> {
let mut i = 0;
loop {
let fr = FooRef(f);
if i == *fr.0 {
return fr;
}
i += 1;
}
}
fn main() {
let mut f = 5;
blah(&mut f);
}
It doesn't compile:
error[E0499]: cannot borrow `*f` as mutable more than once at a time
--> test.rs:6:25
|
6 | let fr = FooRef(f);
| ^
| |
| second mutable borrow occurs here
| first mutable borrow occurs here
...
12 | }
| - first borrow ends here
If I understand this error, it's saying that f
can be borrowed until the end of the function on one loop iteration, then borrowed again on a second iteration, which doesn't work.
This doesn't seem right to me; either fr
goes out of scope (and thus is returned before it says) or it returns (and there's no subsequent borrow).
Is there any way to express this that will compile?