0

I have a struct with method fn maybe_getv(&mut self) -> Option<&mut i32>. Now I want to implement another function called "getv_with_retry" that keep retrying in a loop and return on success.

struct S {
    v: i32,
}

impl S {
    pub fn maybe_getv(&mut self) -> Option<&mut i32> {
        unimplemented!();  // return Some(&mut self.v) in some cases
    }
}

fn getv_with_retry(s: &mut S) -> Option<&mut i32> {
    loop {
        let result = s.maybe_getv();
        if result.is_some() {
            return result;
        }
    }
}

(link to rust playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f6ca3e7d0a6c29a0e9d9cdcf902c7ad3)

The compiler would report the following error:

error[E0499]: cannot borrow `*s` as mutable more than once at a time
  --> src/lib.rs:13:22
   |
11 | fn getv_with_retry(s: &mut S) -> Option<&mut i32> {
   |                       - let's call the lifetime of this reference `'1`
12 |     loop {
13 |         let result = s.maybe_getv();
   |                      ^^^^^^^^^^^^^^ `*s` was mutably borrowed here in the previous iteration of the loop
14 |         if result.is_some() {
15 |             return result;
   |                    ------ returning this value requires that `*s` is borrowed for `'1`

How should I correctly implement getv_with_retry?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
BlahGeek
  • 41
  • 1
  • 4

0 Answers0