rust的哈希表-元素更新

时间:2024-02-21 11:45:22
fn main() {  
    use std::collections::HashMap;
    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    let team_list =["Blue","Red"];
    for i in team_list{
        if scores.contains_key(i){
            scores.insert(i.to_string(), scores[i]+50);
        }else{
            scores.insert(i.to_string(), 50);
        }
    }
    println!("{:?}",scores);//{"Red": 50, "Blue": 60, "Yellow": 50}
}
fn main() {  
    use std::collections::HashMap;
    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    let team_list =["Blue","Red"];
    for i in team_list{
        let count = scores.entry(i.to_string()).or_insert(0);
        *count += 50;
    }
    println!("{:?}",scores);//{"Red": 50, "Blue": 60, "Yellow": 50}
}

相比contains_key+insert ,这种方法更优雅