`IndexMut` problems for recursive maps

I have a data structure which consists of recursive maps.
How can I look into this data structure with indexes?

As in:

pub struct Files {
    pub folders: HashMap<&'static Path, Files>,
    pub files: HashSet<&'static Path>,
}

impl Files {
    pub fn move_layer_up(&mut self, path: &'static Path) { }
}

fn main() {
    ...
    let p = |name| Path::new(name);

    // Works, but ugly
    files
        .folders
        .get_mut(p("headers"))
        .unwrap()
        .folders
        .get_mut(p("vostok"))
        .unwrap()
        .move_layer_up(p("__root"));

    // Doesn't work, cannot borrow data in an index
    files.folders[p("headers")].folders[p("vostok")].move_layer_up(p("__root"));
}

Implement the traits on your own type. Or just have a get_mut method of your own that does the same thing.

1 Like

Yep, thanks! Still wonder why I couldn't just use HashMap indexing instead.

As the error says, it doesn't implement IndexMut. The idea being that this should never panic, even if some_key isn't in the map yet.

hash_map[some_key] = some_value;
1 Like