1

The following code won't compile:

fn test<'a>(index: usize, v: &'a mut Vec<i32>) -> Option<&'a i32> {
    {
        let t = v.get(index);
        if t.is_some() {
            return t
        }
        //return t
    }
    v.insert(index, index as i32 + 1);
    v.get(index)
}
error[E0502]: cannot borrow `*v` as mutable because it is also borrowed as immutable
  --> src/main.rs:9:5
   |
3  |         let t = v.get(index);
   |                 - immutable borrow occurs here
...
9  |     v.insert(index, index as i32 + 1);
   |     ^ mutable borrow occurs here
10 |     v.get(index)
11 | }
   | - immutable borrow ends here

I thought this code would be fine because the immutable borrow occurs in an inner block. What's weird is that if I remove the if-clause and just return "t" in the inner block then the code compiles fine.

Am I missing something here? I am using Rust 1.22.1 on Linux.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • [The duplicate applied to your question](https://play.integer32.com/?gist=4303a118a8ef278959c3bfc8fecd4f1e&version=stable). – Shepmaster Dec 10 '17 at 22:25

0 Answers0