(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
}

相关推荐
传奇开心果编程26 分钟前
【Rust入门知识点学与练】第3课:String 与 &str 的区别
开发语言·学习·rust
tedcloud1235 小时前
OpenLogi 怎么搭建?用 Rust 打造一个轻量的 Logitech 外设管理工具
linux·运维·服务器·开发语言·后端·rust·开源
传奇开心果编程6 小时前
【Rust入门知识点学与练】第5课:函数
开发语言·学习·rust
传奇开心果编程7 小时前
【Rust入门知识点学与练】第9课:Vec 动态数组
开发语言·学习·rust
yume_sibai7 小时前
02-Rust 所有权与借用深入解析(底层原理 + 借用检查器 + 生命周期 + 内部可变性)
开发语言·后端·rust
传奇开心果编程7 小时前
【Rust入门知识点学与练】第1课变量与打印
开发语言·学习·rust
梦醒沉醉8 小时前
std1.97.1——default模块和clone模块总览
rust
小灰灰搞电子1 天前
Rust std::vec::Vec<T>动态数组:所有相关 API 全面介绍
开发语言·rust
学习星球1 天前
CodeWhale 深度剖析:从 DeepSeek-TUI 到 40.9K Star 的 Rust 终端编程 Agent
开发语言·后端·rust
小灰灰搞电子1 天前
Rust 相关容器(集合)详解
开发语言·容器·rust