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));
    
}
相关推荐
kfaino3 小时前
码农的AI翻身(五)你好,我叫 Transformer
后端·aigc
Oneslide9 小时前
机械革命 单系统纯净重装Ubuntu(全盘覆盖,清空原有Windows)
后端
GetcharZp9 小时前
告别OOM!用Go+libvips实现30000×50000超大图片的流式瓦片服务
后端·go
IT_陈寒10 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户479492835691510 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
神奇小汤圆11 小时前
2026一线大厂Java八股文精选(附答案,高质量整理)
后端
Warson_L12 小时前
LangGraph入门学习资料
后端
神奇小汤圆12 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
后端
kfaino13 小时前
码农的AI翻身(四)你好,我叫 Attention
人工智能·后端
lwx5728013 小时前
探秘InnoDB:搞懂它的内存、线程、磁盘与日志刷盘策略
java·后端