1
\$\begingroup\$

Before anyone marks this as duplicate, my question is only towards the median, and my approach is different from what the answer suggested. On getting the mode from a vector of values, I have the below:

fn get_mode(list_of_numbers: &[i32]) -> i32 {
    // most common occurrence of item from vector
    use std::collections::HashMap;
  

    //* using structs.More readable
    struct Mode {
        number: i32,
        frequency: u32,
    };

    let mut occurence = HashMap::new();

    let mut most_common: Mode = Mode {
        number: 0,
        frequency: 0,
    };

    for number in list_of_numbers {
        let count = occurence.entry(number).or_insert(0);
        *count += 1;
    }

    for (&key, val) in occurence {
        if val > most_common.frequency {
            most_common = Mode {
                number: key,
                frequency: val,
            };
        }
    }

    most_common.number
}

For readability, the function uses a struct. My question comes down to :

    for (&key, val) in occurence {

Why can't I borrow the value val from the HashMap given I might as well be passing the values and keys to another function in this loop? The error when I try:

for (&key, &val) in occurence {

would be : expected integer, found reference. How come?

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to the Code Review site where we review code that is working as expected, if the code is resulting in errors than the question is off-topic for this site. \$\endgroup\$
    – pacmaninbw
    Oct 23 '20 at 17:44
  • \$\begingroup\$ The code @pacmaninbw works. My question is why it would not work if the borrowing happened. \$\endgroup\$ Oct 23 '20 at 17:52

Browse other questions tagged or ask your own question.