Here is a simple program which looks up previous value in map
and puts a new value into it. It won't compile as the first lookup immutably borrows map
and insert
wants to mutably borrow map
.
use std::collections::HashMap;
fn main() {
let mut map: HashMap<i32, i32> = HashMap::new();
map.insert(0, 0);
(1..5).for_each(|x| {
let prev = map.get(&(x - 1)).unwrap();
map.insert(x, (prev + 1) * 10);
});
map.iter().for_each(|(k, v)| println!("{} -> {}", k, v));
}
The problem can be solved by using clone()
on to get prev
as
let prev = map.get(&(x - 1)).unwrap().clone();
and get the output as:
0 -> 0
1 -> 10
2 -> 110
3 -> 1110
4 -> 11110
What can I do to not use clone()
here?