In the following Rust code I am calculating mode for a vector of ints. See lines 38 and 42, I have to dereference k there. If I do, it compiles and runs OK. If I don't - I get error "expected i32, found &i32" (see after the code snippet). Why the reference to value (as I do &v in line 34) gives me value but the reference to the key gives me yet another reference, which I have to dereference to get to actually key?
use std::collections::HashMap;
fn mode(v: &Vec<i32>) -> i32 {
let mut h = HashMap::new();
for x in v {
let counter = h.entry(x).or_insert(0);
*counter += 1;
}
let mut last_key: Option<i32> = None;
let mut last_value: Option<i32> = None;
for (&k, &v) in &h {
println!("k, v: {}, {}", k, v);
match last_value {
Some(x) => {
if x > v {
last_key = Some(*k);
last_value = Some(v)
}
}
None => {
last_key = Some(*k);
last_value = Some(v)
}
}
}
if let Some(x) = last_key {
x
} else {
panic!("empty list");
}
}
error[E0308]: mismatched types --> src/main.rs:38:33
| 38 | last_key = Some(k);
| ^
| |
| expected `i32`, found `&i32`
| help: consider dereferencing the borrow: `*k`