(done) 速通 rustlings(17) 哈希表

哈希表的导入、创建、插入

如下代码,是哈希表的导入、创建、插入:

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

fn fruit_basket() -> HashMap<String, u32> {
    // Declare the hash map.
    let mut basket = HashMap::new();

    // Two bananas are already given for you :)
    basket.insert(String::from("banana"), 2);

    // Put more fruits in your basket.
    basket.insert(String::from("apple"), 3);
    basket.insert(String::from("mango"), 1);

    basket
}

若不存在,则插入

RUST 哈希表有些很方便的内置函数:

比如 basket.entry(fruit).or_insert(5); 表示 "若表中不存在 fruit,则插入该 key,value 设置为 5"

rust 复制代码
enum Fruit {
    Apple,
    Banana,
    Mango,
    Lychee,
    Pineapple,
}

fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
    let fruit_kinds = [
        Fruit::Apple,
        Fruit::Banana,
        Fruit::Mango,
        Fruit::Lychee,
        Fruit::Pineapple,
    ];

    for fruit in fruit_kinds {
        // If fruit doesn't exist, insert it with some value.
        basket.entry(fruit).or_insert(5);
    }
}

对哈希表中项的访问

可以使用 entry 内置函数访问哈希表中的项

or_default() 表示若表中不存在该 key,则插入该 key,value 设置为默认值

rust 复制代码
fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> {
    // The name of the team is the key and its associated struct is the value.
    let mut scores = HashMap::<&str, TeamScores>::new();

    for line in results.lines() {
        let mut split_iterator = line.split(',');
        // NOTE: We use `unwrap` because we didn't deal with error handling yet.
        let team_1_name = split_iterator.next().unwrap();
        let team_2_name = split_iterator.next().unwrap();
        let team_1_score: u8 = split_iterator.next().unwrap().parse().unwrap();
        let team_2_score: u8 = split_iterator.next().unwrap().parse().unwrap();

        // Insert the default with zeros if a team doesn't exist yet.
        let team_1 = scores.entry(team_1_name).or_default();
        // Update the values.
        team_1.goals_scored += team_1_score;
        team_1.goals_conceded += team_2_score;

        // Similarly for the second team.
        let team_2 = scores.entry(team_2_name).or_default();
        team_2.goals_scored += team_2_score;
        team_2.goals_conceded += team_1_score;
    }

    scores
}

相关推荐
星栈独行9 小时前
Makepad 应用如何读文件、调接口、保存数据
前端·程序人生·ui·rust·github
guyoung11 小时前
BoxAgnts 工具系统(7)——Skill 模板、Agent 代理与 Cron 调度
rust·agent·ai编程
分布式存储与RustFS14 小时前
基于Rust的国产开源对象存储RustFS:S3 Table对Iceberg数据湖的适配详解
rust·开源·iceberg·对象存储·rustfs·minio平替·s3 table
Jinkxs17 小时前
Rust 性能优化全流程:从 flamegraph 定位瓶颈到 unsafe 与 SIMD 加速,响应快 2 倍
开发语言·性能优化·rust
星栈独行20 小时前
Rust + Makepad 应用怎么打包发布:Windows、macOS、Linux 全平台交付
windows·程序人生·macos·ui·rust
fox_lht1 天前
15.3.改进我们之前的输入、输出项目
开发语言·后端·学习·rust
guyoung2 天前
BoxAgnts 工具系统(6)——多 Provider 适配与 Agent 查询循环
rust·agent·ai编程
星栈2 天前
Rust + Makepad 应用怎么打包发布:Windows、macOS、Linux 全平台交付
前端·rust
MageGojo2 天前
R-Shell开源项目实战解析:用Rust打造命令行SSH工具,支持连接管理、远程执行、SFTP与MCP
运维·rust·开源项目·命令行工具·ssh客户端·mcp
techdashen2 天前
Cargo 1.94 开发周期全解析
开发语言·后端·rust