I want to create a function which gets the value associated to a key in a hashtable, and, if such value does not exist, inserts an arbitrary value (let us say 0).
use std::collections::HashMap;
fn get_or_insert(table: &mut HashMap<i32, i32>, key: i32) -> i32 {
match table.get(&key) {
None => table.insert(key, 0).unwrap(),
Some(v) => *v,
}
}
This code does not compile:
error[E0502]: cannot borrow `*table` as mutable because it is also borrowed as immutable
--> src/main.rs:5:17
|
4 | match table.get(&key) {
| ----- immutable borrow occurs here
5 | None => table.insert(key, 0).unwrap(),
| ^^^^^ mutable borrow occurs here
6 | Some(v) => *v,
7 | }
| - immutable borrow ends here
Indeed, table
is mutably borrowed in the method insert
whereas it is immutably borrowed in the method get
.
I can see no way to separate the mutable and immutable parts in this function.