rust --hashmap学习

hash map:
    HashMap<K, V>存储映射关系:类型K 到 类型V的映射;实现中使用hashing函数,决定key和value在内存中如何安置;
    
    创建: hash map存储data在heap上;
        using std::collections::HashMap;
        
        let mut scores = HashMap::new();
        scores.insert(String::from("Blu"), 10);
        scores.insert(String::from("Yel"), 50);
        
        或者通过迭代vector元组来构建;
        use std::collections::HashMap;

        let teams = vec![String::from("Blue"), String::from("Yellow")];
        let initial_scores = vec![10, 50];

        let mut scores: HashMap<_, _> =
            teams.into_iter().zip(initial_scores.into_iter()).collect();
        
        实现Copy Trait的数据结构,value值被拷贝到hash map中;对于owned类型,值将被移动并且hash map将拥有value;
            use std::collections::HashMap;

        let field_name = String::from("Favorite color");
        let field_value = String::from("Blue");
        
        let mut map = HashMap::new();
        map.insert(field_name, field_value);
        // field_name and field_value are invalid at this point, try using them and
        // see what compiler error you get!
        
        
    访问:
        let team_name = String::from("Blue");
        let score = scores.get(&team_name);  //被封装尽Some,get方法返回一个Option<&V>
        
        for (key, value) in &scores {        //迭代访问;
            println!("{}: {}", key, value);
        }
        
    更新:
        (1)覆盖更新:scores.insert(String::from("Blue"), 25);
        (2)非覆盖更新:scores.entry(String::from("Yellow")).or_insert(50);
        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值