Unwrapping options

#[derive(Debug)]
struct Foo {
    name: String,
    val: String,
}
use std::collections::HashMap;

struct Bar {
    pub map: Option<HashMap<String, Vec<Foo>>>,
}

fn fun(bar: Bar, key: &str) {
    let vec = Vec::new();
    
    let vec = if let Some(map) = bar.map {
        if let Some(vec) = map.get(key) {
            vec
        } else {
            &vec
        }
    } else {
      &vec
    };
}
  

in fun() I'm unwrapping bar first but it is taking around 10 lines (and this number of lines will increase if argument bar is option). is there any easy way doing this which will occupy lesser line of code?

fn fun(bar: Bar, key: &str) {
    let vec = Vec::new();
    
    let vec = bar.map
        .as_ref()
        .and_then(|map| map.get(key))
        .unwrap_or(&vec);
}

I encourage you to check out the documentation for the methods I used above. (The as_ref method is defined directly on Option, and is not the method from the AsRef trait.)

8 Likes

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.