Rust HashMap

一、HashMap是什么,怎么用

1、HashMap是什么

HashMap 也是 Rust 标准库中提供的集合类型,但是又与动态数组不同,HashMap 中存储的是一一映射的 KV 键值对 ,并提供了平均时间复杂度为 O(1) 的查询方法

2、HashMap怎么用

(1)创建哈希表

使用new 方法创建

rust 复制代码
use std::collections::HashMap;//注意要导入包

// 创建一个HashMap,用于存储宝石种类和对应的数量
let mut my_gems = HashMap::new();

// 将宝石类型和对应的数量写入表中
my_gems.insert("红宝石", 1);
my_gems.insert("蓝宝石", 2);
my_gems.insert("河边捡的误以为是宝石的破石头", 18);

使用collection创建

rust 复制代码
fn main() {
    use std::collections::HashMap;

    let teams_list = vec![
        ("中国队".to_string(), 100),
        ("美国队".to_string(), 10),
        ("日本队".to_string(), 50),
    ];

    let teams_map: HashMap<_,_> = teams_list.into_iter().collect();
    
    println!("{:?}",teams_map)
}

元组数据直接创建

rust 复制代码
use std::{collections::HashMap};
fn main() {
    let teams = [
        ("Chinese Team", 100),
        ("American Team", 10),
        ("France Team", 50),
    ];

    let mut teams_map1 = HashMap::new();
    for team in &teams {
        teams_map1.insert(team.0, team.1);
    }

    let teams_map2 = HashMap::from(teams);
    assert_eq!(teams_map1, teams_map2);

    println!("Success!")
}

(2)哈希表的元素所有权转移

即放入元素到哈希表中也会发生所有权转移

rust 复制代码
fn main() {
    use std::collections::HashMap;

    let name = String::from("Sunface");
    let age = 18;

    let mut handsome_boys = HashMap::new();
    handsome_boys.insert(name, age);

    println!("因为过于无耻,{}已经被从帅气男孩名单中除名", name);
    println!("还有,他的真实年龄远远不止{}岁", age);
}

(3) 获取哈希表中的元素

rust 复制代码
use std::collections::HashMap;

let mut scores = HashMap::new();

scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);

let team_name = String::from("Blue");
let score: Option<&i32> = scores.get(&team_name);
  1. get 方法返回一个 Option<&i32> 类型:当查询不到时,会返回一个 None,查询到时返回 Some(&i32)
  2. &i32是对 HashMap 中值的借用,如果不使用借用,可能会发生所有权的转移

(4)遍历哈希表中的元素

rust 复制代码
use std::collections::HashMap;

let mut scores = HashMap::new();

scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);

for (key, value) in &scores {
    println!("{}: {}", key, value);
}

(5)哈希表插入新值

rust 复制代码
fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();

    scores.insert("Blue", 10);
}

(6)没有则插入

rust 复制代码
fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();

    scores.insert("Blue", 10);
    // 查询Yellow对应的值,若不存在则插入新值
    let v = scores.entry("Yellow").or_insert(5);
    assert_eq!(*v, 5); // 不存在,插入5
}

(7)已有则更新

rust 复制代码
fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();

    scores.insert("Blue", 10);

    // 覆盖已有的值
    let old = scores.insert("Blue", 20);//覆盖
    assert_eq!(old, Some(10));
    
}
相关推荐
wstcl22 分钟前
让你的asp.net网站在调试模式下也能在局域网通过ip访问
后端·tcp/ip·asp.net
GuokLiu28 分钟前
250708-通过两块硬盘拷贝DeepSeek两个满血版模型的bash脚本
开发语言·chrome·bash
iCxhust7 小时前
c# U盘映像生成工具
开发语言·单片机·c#
yangzhi_emo8 小时前
ES6笔记2
开发语言·前端·javascript
ai小鬼头8 小时前
Ollama+OpenWeb最新版0.42+0.3.35一键安装教程,轻松搞定AI模型部署
后端·架构·github
emplace_back8 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
jz_ddk9 小时前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
萧曵 丶9 小时前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust
xiaolang_8616_wjl9 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源