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));
    
}
相关推荐
IT_陈寒10 小时前
Python开发者必知的5大性能陷阱:90%的人都踩过的坑!
前端·人工智能·后端
范特西林11 小时前
一次 to_bits() 引发的 Rust 与 C++ 底层思考
rust
流浪克拉玛依11 小时前
Go Web 服务限流器实战:从原理到压测验证 --使用 Gin 框架 + Uber Ratelimit / 官方限流器,并通过 Vegeta 进行性能剖析
后端
孟沐11 小时前
保姆级教程:手写三层架构 vs MyBatis-Plus
后端
星浩AI11 小时前
让模型自己写 Skills——从素材到自动生成工作流
人工智能·后端·agent
华仔啊13 小时前
为啥不用 MP 的 saveOrUpdateBatch?MySQL 一条 SQL 批量增改才是最优解
java·后端
武子康14 小时前
大数据-242 离线数仓 - DataX 实战:MySQL 全量/增量导入 HDFS + Hive 分区(离线数仓 ODS
大数据·后端·apache hive
砍材农夫14 小时前
TCP和UDP区别
后端
千寻girling15 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
千寻girling15 小时前
Python 是用来做 AI 人工智能 的 , 不适合开发 Web 网站 | 《Web框架》
人工智能·后端·算法