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

I am trying to implement a dynamic programming problem in Rust to get to know the language. Like many problems with dynamic programming, memoization is used to reduce runtime. Unfortunately, my solution to the first exit gives errors. I fixed the code until the next. Warning - now this is a little pointless:

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() {} 

Compilation Error:

 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 memo variable borrowed several times? In my opinion, it should be borrowed once when I calculate script_a , then this loan ends, then it is borrowed again for script_b .

+2
rust
source share
2 answers

Currently takes the last place for the block in which they are defined ( # 9113 may change this if implemented)

The problem is that script_a (which contains an immutable map link) is valid for the entire block, and you are trying to use a mutable link to the same map:

 let script_a = repro(memo); let script_b = repro(memo); // script_a is still alive 
+3
source share

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

0
source share

All Articles