The code below works, but I suspect someone with more Rust experience would write it differently.
How would you improve this?
I imagine I would also add use of the Iterator
min_by_key
method, but it probably wouldn't be fewer lines of code.
use std::collections::HashMap;
fn get_shortest(months: HashMap<String, i8>) -> String {
let mut shortest: i8 = 32;
let mut name = String::new();
for (key, val) in months.iter() {
if val < &shortest { // not happy with needing &
name = key.to_string(); // not happy with needing .to_string()
shortest = *val; // not happy with needing *
}
}
name
}
fn main() {
let mut days_in_month: HashMap<String, i8> = HashMap::new();
days_in_month.insert("January".to_string(), 31);
days_in_month.insert("February".to_string(), 28);
days_in_month.insert("March".to_string(), 31);
days_in_month.insert("April".to_string(), 30);
println!("shortest = {}", get_shortest(days_in_month));
}
Output:
shortest = February
Errors:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 1.59s
Running `target/debug/playground`