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

相关推荐
Java水解7 小时前
Rust异步编程实战:构建高性能网络应用
后端·rust
土豆12507 小时前
Rust 实战:手把手教你开发一个命令行工具
前端·rust
勇敢牛牛_7 小时前
【aiway】基于 Rust 开发的 API + AI 网关
开发语言·后端·网关·ai·rust
Source.Liu15 小时前
【Iced】`lib.rs` 源码分析 - `iced_core` 核心库
rust·iced
古城小栈15 小时前
Rust跨平台编译打包 之 三大战役
开发语言·后端·rust
was17216 小时前
基于 Rust 的跨 Shell 提示符:Starship 安装与环境初始化指南
开发语言·elasticsearch·rust
rainchestnut1 天前
bevy初体验2-官方示例学习
rust
葡萄城技术团队1 天前
Hurley:用 Rust 打造的高性能 HTTP 客户端 + 压测工具
开发语言·http·rust
Source.Liu2 天前
【dxf-rs】库全面介绍
rust·dxf-rs
土豆12502 天前
Rust宏编程完全指南:用元编程解锁Rust的终极力量
rust·编程语言