Iterate and modify a HashMap in single line

how can I write for loop in below code in a single line

fn update_map(mut arg:HashMap<i32,&str>) {
    let mut default_map = HashMap::from([(1,"abc"),(2,"def"),(3,"ghi")]);
    for (k,v) in default_map.iter() {
      if arg.contains_key(k) == false {
        arg.insert(*k, v);
      }
    } 
}

You can save a bit of verbosity by using the entry API:

for (k, v) in default_map.iter() {
    arg.entry(*k).or_insert(v);
}

"In a single line" is not really an accurate requirement... technically everything is possible in a single line: just don't use line-breaks!

for (k, v) in default_map.iter() { arg.entry(*k).or_insert(v); }
3 Likes

If you can return a new HashMap try

fn update_map(arg: &HashMap<i32,&str>) -> HashMap<i32, &str> {
    [(1,"abc"),(2,"def"),(3,"ghi")]
        .into_iter()
        .chain(arg)
        .collect()
}