Nested hashmap update successfully?

Trying to Create a hashmap of hashmap of the form
// 01: {Start:xx, End:xx, Time:xx}, 02: {Start:xx, End:xx,Time:xx}

let file = File::open(&filename)?;
    let mut map1:HashMap<String,HashMap<String,String>> = 
    let mut reader = BufReader::new(file);
    let mut line = String::new();
    loop {
        match reader.read_line(&mut line) {
        Ok(bytes_read) => {
            if bytes_read == 0 {
                return Ok(());
            if const_identity.starts_with("A") {
                    //Inner hashmap 
                    let mut map2:HashMap<String,String> = HashMap::with_capacity(10);
                    map2.insert("start".to_string(),time_start.to_string() );
                } else if const_identity.starts_with("B") {
                    // Error  
                    let map2:&HashMap<String, String>
                        =  &mut map1.get_mut(&thread_num.to_string() ).unwrap();


The compiler tells me


cannot borrow *map2 as mutable, as it is behind a & reference

map2 is a & reference, so the data it refers to cannot be borrowed as mutable

How do I update the inner hashmap ?

It's because the type annotation on map2 is an immutable reference, so the mutable reference returned by get_mut was downgraded. Either remove the type annotation or change it to a mutable reference. You also should not have an &mut in front of the get_mut call.

let map2 = map1.get_mut(&thread_num).unwrap();
map2.insert(count.to_string(), time_count.to_string());

In the future, please post errors in codeblocks exactly as printed by cargo build. It's easier to read that way.

Thanks . That helped . But now I am getting this error .

                    let map2 = map1.get_mut(&thread_num.to_string() ).unwrap() ;
error[E0308]: mismatched types
  --> src/
70 |                     map1.insert(thread_num.to_string(),map2);
   |                                                        ^^^^ expected struct `HashMap`, found mutable reference
   = note:         expected struct `HashMap<String, String>`
           found mutable reference `&mut HashMap<String, String>`

You should not try to insert it again. It's already in map1. The get_mut method does not return a clone.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.