Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Rust want to borrow a variable as mutable more than once at a time?

Tags:

rust

I'm attempting to implement a dynamic programming problem in Rust to gain familiarity with the language. Like many dynamic programming problems, this uses memoization to reduce the running time. Unfortunately, my first-pass solution yields errors. I've pared the code down to the following. Warning - it's now a bit nonsensical:

use std::collections::HashMap;

fn repro<'m>(memo: &'m mut HashMap<i32, Vec<i32>>) -> Option<&'m Vec<i32>> {
    {
        let script_a = repro(memo);
        let script_b = repro(memo);
    }

    memo.get(&0)
}

fn main() {}

The compilation error is:

error[E0499]: cannot borrow `*memo` as mutable more than once at a time
 --> src/main.rs:6:30
  |
5 |         let script_a = repro(memo);
  |                              ---- first mutable borrow occurs here
6 |         let script_b = repro(memo);
  |                              ^^^^ second mutable borrow occurs here
7 |     }
  |     - first borrow ends here

Why is the variable memo borrowed multiple times? In my view, it should be borrowed once when I compute script_a, then that borrow ends, then it gets borrowed again for script_b.

like image 684
Shepmaster Avatar asked Sep 30 '22 09:09

Shepmaster


1 Answers

Currently borrows last for the block they are defined in (#9113 might change this if implemented)

The problem is that script_a (that holds an immutable reference to a map) is valid for the whole block and you try to use a mutable reference to the same map:

let script_a = repro(memo);
let script_b = repro(memo);
// script_a is still alive
like image 92
Arjan Avatar answered Oct 16 '22 07:10

Arjan