1

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");
    }
}

Playgorund

 error[E0308]: mismatched types   --> src/main.rs:38:33    
 | 38 |            last_key = Some(k);    
 |                                 ^           
 |                                 |
 |                                 expected `i32`, found `&i32`   
 |                                 help: consider dereferencing the borrow: `*k`
Aiden4
  • 2,504
  • 1
  • 7
  • 24
peroksid
  • 890
  • 6
  • 17
  • 5
    When iterating `&Vec` in lines 28 to 31, the type of `x` is `&i32`—and consequently that is also the type of the keys in your HashMap `h`. – eggyal Oct 18 '21 at 23:02
  • 2
    Not really relevant to your issue, but you should also take a look at [why functions shouldn't accept an `&Vec`](https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-to-a-string-string-vec-vec-o) – Aiden4 Oct 18 '21 at 23:17

1 Answers1

1

because when you iter over &Vec, the value of x is &i32, so the key of hashmap is &i32, the value is i32

for (&k, &v) in &h

and when you iter over &h, the key value pair is (&&i32, &i32), but you match the key value with &, so here k is &i32 and v is i32, so you have to dereferenc k here

Sean
  • 2,990
  • 1
  • 21
  • 31