HashMap with vector values


#1

This code will not compile

use std::collections::HashMap;
struct Fud {
    keys:Vec<String>
}
fn foo(fud:&Fud){
    let mut results:HashMap<&String, Vec<f64>> = HashMap::new();
    for k in fud.keys.iter() {
        results.insert(k, Vec::new());
    }
    for v in fud.keys.iter() {
        results.get(v).unwrap().push(0.0);
    }    
}
fn main() {
    let fud = Fud{keys:vec!["a".to_string(), "b".to_string(), "c".to_string()]};
    foo(&fud);
}
   |         ^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable

Obviously I have the borrowing rules wrong in my head. But since results is declared mut I thought that meant all its fields were mut too.

How can I have a mut HashMap with &String as keys and Vec<f64> as value?


#2

The get method only takes &self, so it’s immutable – use get_mut instead.


#3

Bingo! Duh!

thank you