I am trying to get started with Rust, and wondered how the following piece of c++ code can be converted to rust.
Consider this C++ code:
void func(int c) {
unordered_map<int, int> map;
auto& a = map[10];
auto& b = map[20];
// some complex logic
if (c > 10) {
a += 1;
b += 1;
} else {
a += 2;
b += 2;
}
cout << map[10] << " " << map[20] << '\n';
}
Right now, I have replaced some complex logic
with a simple if/else, but in essence, I need two mutable references to two values inside my hash map.
Consider the corresponding rust code:
fn func(c: i32) {
let mut map = HashMap::new();
let a = map.entry(&10).or_insert(0);
let b = map.entry(&20).or_insert(0);
// some complex code here
if c > 10 {
*a += 1;
*b += 1;
} else {
*a += 2;
*b += 2;
}
}
rustc
will not compile this code because I have two mutable references to map here.
How should one go about doing this in rust?