Why does Rust want to borrow a variable as mutable

2020-04-11 05:49发布

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.

标签: rust
2条回答
不美不萌又怎样
2楼-- · 2020-04-11 06:03

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
查看更多
放荡不羁爱自由
3楼-- · 2020-04-11 06:21

The bigger problem is the infinite loop. Anyway let script_a is a reference to data inside the hash map, so it's still borrowed by the time you call let script_b = repro(memo);.

查看更多
登录 后发表回答