# Help with understanding the borrow checker

**URL:** <https://users.rust-lang.org/t/help-with-understanding-the-borrow-checker/59643>\
**Category:** help\
**Created:** [May 10, 2021, 2:46pm UTC](https://users.rust-lang.org/t/help-with-understanding-the-borrow-checker/59643 "2021-05-10T14:46:05Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![danben](https://avatars.discourse-cdn.com/v4/letter/d/9fc348/32.png) [@danben](https://users.rust-lang.org/u/danben)\
**Post date:** [May 10, 2021, 2:46pm UTC](https://users.rust-lang.org/t/help-with-understanding-the-borrow-checker/59643/1 "2021-05-10T14:46:05Z")

</div>

I have the following code snippet:

```
  fn does_not_work(t: &mut HashMap<String, i32>) -> &i32 {    
     let k = String::from("key"); 
     match t.get(&k)
         Some(v) => &v,    
         None => {   
             let v = 1; 
             t.insert(k, v);    
             &v     
         }    
     }    
  }  

```

It gives an error when trying to call t.insert: " cannot borrow `*t` as mutable because it is also borrowed as immutable". I assume this is because the result of the call to `get` is still in scope, and the borrow checker does not know enough to differentiate the `Some` case, which has a reference to data inside the table, from the `None` case. Is that correct?

If I then change the code to return a copy rather than a reference:

```
  pub fn works(t: &mut HashMap<String, i32>) -> i32 {
      let k = String::from("key");
      match t.get(&k) {
          Some(v) => *v,
          None => {
              let v = 1;
              t.insert(k.clone(), v);
              v
          }
      }
  }

```

This compiles without errors. Why is that? I'm still calling `insert` while holding onto the option.

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [May 10, 2021, 2:53pm UTC](https://users.rust-lang.org/t/help-with-understanding-the-borrow-checker/59643/2 "2021-05-10T14:53:55Z")

</div>

This is a well known problem in the compiler where it rejects code that it should accept. The problem is that if you do something that borrows a variable (here `t`) and then _returns_ the resulting borrow (here `v`) from the function, then it marks the variable (here `t`) as borrowed for the rest of the function in all possible execution paths from there, not just the ones where it gets returned.

Note: Returning the local `v` variable in your `None` branch could never work. You would have to call `get` again into the `HashMap` to get a reference that actually points inside the `HashMap` rather than one that points to the local variable, which is destroyed when you return. But once you fix that, you run into what I described above.

The version that works works because you don't return any references.

---

<div class="post-metadata">

**Author:** ![danben](https://avatars.discourse-cdn.com/v4/letter/d/9fc348/32.png) [@danben](https://users.rust-lang.org/u/danben)\
**Post date:** [May 10, 2021, 3:02pm UTC](https://users.rust-lang.org/t/help-with-understanding-the-borrow-checker/59643/3 "2021-05-10T15:02:18Z")

</div>

Got it, thanks. This specific case aside, is there a correct workaround for the general problem illustrated here?

---

<div class="post-metadata">

**Author:** ![jameseb7](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/jameseb7/32/13257_2.png) [@jameseb7](https://users.rust-lang.org/u/jameseb7)\
**Post date:** [May 10, 2021, 3:22pm UTC](https://users.rust-lang.org/t/help-with-understanding-the-borrow-checker/59643/4 "2021-05-10T15:22:51Z")

</div>

This looks like it is doing the same as the following using the [entry API](https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html):

```rust
t.entry(k).or_insert(1)

```

This returns an `&mut` reference to the value already in the map (if any), or the newly inserted value if there is none.

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [May 10, 2021, 3:26pm UTC](https://users.rust-lang.org/t/help-with-understanding-the-borrow-checker/59643/5 "2021-05-10T15:26:28Z")

</div>

In the specific case of `HashMap`, the entry API is the right answer.

However, the same problem can occur in other cases. Here you can usually work around it by performing the borrow twice. For example:

```rust
fn works(t: &mut HashMap<String, i32>) -> &i32 {
   let k = String::from("key");
   match t.get(&k)
       Some(v) => t.get(&k).unwrap(),
       None => {
           ...
       }
   }
}

```

This would work because the borrow that is ultimately returned is not created until after it enters the `Some` branch, so the `None` branch is not included in "all possible execution paths from that borrow".

Sometimes there are entirely alternate rewritings you could do as well:

```rust
fn works(t: &mut HashMap<String, i32>) -> &i32 {
   let k = String::from("key");
   if !t.contains_key(&k) {
      t.insert(k.clone(), 1);
   }
   t.get(&k).unwrap()
}

```

But again, the entry API is the right answer for `HashMap`.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [August 8, 2021, 3:26pm UTC](https://users.rust-lang.org/t/help-with-understanding-the-borrow-checker/59643/6 "2021-08-08T15:26:44Z")

</div>

Closed on August 8, 2021, 3:26pm UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
