Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find X in a HashMap of HashMaps?

Given that I know ParentId and ChildId, how would I find the UserId if the hashmap is:

HashMap<ParentId, HashMap<ChildId, HashMap<UserId, Foobar>>>

As my knowledge about Rust is pretty basic, I found that the following works but its quite verbose, as I don’t know any better

match foobar.get(&pid) {
  Some(data1) => {
    println!("Found 1: {:?}", data1);

   match data1.get(&cid) {
     Some(data2) => {
      println!("Found 2: {:?}", data2);       
      
      ...and so on
     }, 
     _ => println!("Not found")     
   }
  },
  _ => println!("Not found")
}

I’ve also attempted chained get but it’s tricky and did not find how to do it correctly

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

foobar
        .get(pid)?
        .get(cid)?        
        .get(to_find)

Any hints are appreciated, thank you!

>Solution :

You can use Option::and_then to chain operations that return Option<_>:

let _: Option<&Foobar> = foobar.get(&pid).and_then(|map| map.get(&cid)).and_then(|map| map.get(&to_find));

Example:

use std::collections::HashMap;

fn main() {
    let map: HashMap<i32, HashMap<bool, HashMap<String, bool>>> = HashMap::new();
    let _: Option<&bool> = map
        .get(&123)
        .and_then(|map| map.get(&true))
        .and_then(|map| map.get("foo"));
}

Playground


Your try with ? is also correct but it’ll only work in a function that returns an Option as it returns None from the function the expression is in if any value is None, which is probably the error you’re getting.

fn get(map: &HashMap<i32, HashMap<bool, HashMap<String, bool>>>) -> Option<bool> {
    map.get(&123)?.get(&true)?.get("foo").cloned()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading