Rust borrow checker and early returns

456 views Asked by At

Rust-lang Playground link

struct Foo {
    val: i32
}

impl Foo {
    pub fn maybe_get(&mut self) -> Option<&mut i32> {
        Some(&mut self.val)
    }
    
    pub fn definitely_get(&mut self) -> &mut i32 {
        { // Add closure to ensure things have a chance to get dropped
            if let Some(val) = self.maybe_get() {
                // Explicit return to avoid potential scope sharing with an else block or a match arms.
                return val;
            }
        }

        // One would think any mutable references would not longer be at play at this point

        &mut self.val   
    }
}

I have some code that's similar but more complicated than what is provided above that I've been fighting with for quite a while. The borrow checker is unhappy with the implementation of definitely_get and has the following error

error[E0499]: cannot borrow `self.val` as mutable more than once at a time
  --> src/main.rs:19:9
   |
10 |     pub fn definitely_get(&mut self) -> &mut i32 {
   |                           - let's call the lifetime of this reference `'1`
11 |         {
12 |             if let Some(val) = self.maybe_get() {
   |                                ---------------- first mutable borrow occurs here
13 |                 return val;
   |                        --- returning this value requires that `*self` is borrowed for `'1`
...
19 |         &mut self.val
   |         ^^^^^^^^^^^^^ second mutable borrow occurs here

It seems unreasonable for there to be no way to implement fallback logic with a mutable reference in Rust so I can't imagine there isn't a way.

1

There are 1 answers

0
quittle On

I've managed to fix this with an unfortunately expensive alternative implementation due to how maybe_get is implemented in my non-trivial example.

impl Foo {
    pub fn has_maybe_val(&self) -> bool {
        // Non-trivial lookup...
        true
    }

    pub fn maybe_get(&mut self) -> Option<&mut i32> {
        // Same non-trivial lookup...
        Some(&mut self.val)
    }
    
    pub fn definitely_get(&mut self) -> &mut i32 {
        if self.has_maybe_val() {
            self.maybe_get().unwrap() // Ouch!
        } else {
            &mut self.val
        } 
    }
}