I am trying to insert a key-value pair in a map within a map:
// small section of a bigger code
for (key,val) in my_keys.iter() {
let (_,_,_,_,_,ref mut x) = my_keys[key];
// modifide for this post
x.insert("45".to_string(),("45".to_string(),"45".to_string()));
}
but i am getting:
cannot borrow data in an index of `HashMap<std::string::String, (usize, usize, u8, Vec<usize>, Vec<u8>, HashMap<std::string::String, (std::string::String, std::string::String), BuildHasherDefault<FxHasher>>), BuildHasherDefault<FxHasher>>` as mutable
--> src/colle.rs:89:32
|
89 | let (_,_,_,_,_,ref mut x) = my_keys[key];
| ^^^^^^^^^ cannot borrow as mutable
|
= help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `HashMap<std::string::String, (usize, usize, u8, Vec<usize>, Vec<u8>, HashMap<std::string::String, (std::string::String, std::string::String), BuildHasherDefault<FxHasher>>), BuildHasherDefault<FxHasher>>`
Is there a way to make a map within a map mutable so i can append values ? (and how )
IndexMut was removed from HashMap because people coming from more dynamic languages generally expect that indexing will allow you to insert new elements into the map, which isn't really possible with the design of the IndexMut trait.
Depending on the context you might also be able to just iterate over the map with iter_mut, but it's hard to say from the small example you've given.
hm ... seams i am not that bright to figure it out... given my error maybe posted the wrong question... driven by a wrong assumption ... what actually does the error implies...
in short, you should use iter_mut() instead of iter(): iter() will immutably borrow the HashMap and yields immutable references to the key value pairs. while iter_mut() will give you mut reference to the value.
//let mut outer_map;
for (key, inner) in outer_map.iter_mut() {
inner.5.insert("45".to_string(), (todo!(), todo!()));
}
in your example, the key is actually not used, so you could instead use values_mut() in such cases to iterate only the values and ignore the keys:
for inner in outer_map.values_mut() {
inner.5.insert("45".to_string(), (todo!(), todo!()));
}
edit: just to mention, iter_mut() will give mut reference to the value, but the key is always immutable for HashMap, you can't change the keys in-place, you must take the entry out and re-insert with the modified key in case you really need to.