I'm new to Rust and still getting used to the ownership model. I'm done with chapter 8 of the book and was trying to solve this exercise:
Given a list of integers, use a vector and return the [...] mode (the value that occurs most often; a hash map will be helpful here) of the list.
Here's my solution:
use std::collections::HashMap;
pub fn vectors() {
let mut numbers: Vec<i32> = vec![
12, 15, 6, 44, 6, 32, 77, 77, 77, 77, 77, 94, 6, 2, 67, 0, 25, 14, 84, 81, 59, 31, 7, 9,
];
println!("{:?}", numbers);
// calculating and displaying the mode
let mut numbers_count = HashMap::new();
for num in &numbers {
let count = numbers_count.entry(num).or_insert(0);
*count += 1;
}
let mut mode = 0;
let mut prev_value = 0;
for (key, value) in &numbers_count {
if *value > prev_value {
prev_value = *value;
mode = **key;
}
}
println!("Mode: {}", mode);
}
The code works but... is this considered a good solution? After I finished I searched online and found this alternative which seems to be more accepted. Also, on line 21 I had to use the dereference operator twice; is this ok, or is it considered bad practice?