Rust

2025年07月15日更新 7 人订阅
原价: ¥ 6 限时优惠
专栏简介 Rust编程语言之错误处理 Rust 语言之 flod Rust编程语言之Cargo、Crates.io详解 Rust编程语言之枚举与模式匹配 Rust语言 - 接口设计的建议之受约束(Constrained) Rust编程语言之无畏并发 Rust语言 - 接口设计的建议之灵活(flexible) Rust语言 - 接口设计的建议之显而易见(Obvious) Rust语言 - 接口设计的建议之不意外(unsurprising) Rust 实战:构建实用的 CLI 工具 HTTPie Rust编程语言学习之高级特性 Rust内存管理揭秘:深度剖析指针与智能指针 解决Rust中数组和切片的编译时大小问题 《Rust编程之道》学习笔记一 Rust Async 异步编程 简易教程 使用 Async Rust 构建简单的 P2P 节点 Rust编程语言入门之模式匹配 Rust async 编程 Rust编程语言之编写自动化测试 Rust编程语言之函数式语言特性:迭代器和闭包 《Rust编程之道》学习笔记二 Rust Tips 比较数值 使用 Rust 开发一个微型游戏 Rust编程初探:深入理解Struct结构体 深入理解Rust中的内存管理:栈、堆与静态内存详解 深入理解 Rust 结构体:经典结构体、元组结构体和单元结构体的实现 深入掌握 Rust 结构体:从模板到实例化的完整指南 深入理解Rust中的结构体:逻辑与数据结合的实战示例 深入理解 Rust 枚举:从基础到实践 掌握Rust字符串的精髓:String与&str的最佳实践 全面解析 Rust 模块系统:实战案例与应用技巧 Rust 中的 HashMap 实战指南:理解与优化技巧 掌握Rust模式匹配:从基础语法到实际应用 Rust 中的面向对象编程:特性与实现指南 深入理解 Rust 的 Pin 和 Unpin:理论与实践解析 Rust Trait 与 Go Interface:从设计到实战的深度对比 从零开始:用 Rust 和 Axum 打造高效 Web 应用 Rust 错误处理详解:掌握 anyhow、thiserror 和 snafu Rust 如何优雅实现冒泡排序 链表倒数 K 节点怎么删?Python/Go/Rust 实战 用 Rust 玩转数据存储:JSON 文件持久化实战 Rust实战:打造高效字符串分割函数 如何高效学习一门技术:从知到行的飞轮效应 Rust 编程入门:Struct 让代码更优雅 Rust 编程:零基础入门高性能开发 用 Rust 写个猜数游戏,编程小白也能上手! Rust 入门教程:变量到数据类型,轻松掌握! 深入浅出 Rust:函数、控制流与所有权核心特性解析 从零开始:用 Rust 和 Axum 打造高效 Web 服务 Rust 集合类型解析:Vector、String、HashMap 深入浅出Rust:泛型、Trait与生命周期的硬核指南 Rust实战:博物馆门票限流系统设计与实现 用 Rust 打造高性能图片处理服务器:从零开始实现类似 Thumbor 的功能 Rust 编程入门实战:从零开始抓取网页并转换为 Markdown 深入浅出 Rust:高效处理二进制数据的 Bytes 与 BytesMut 实战 Rust智能指针:解锁内存管理的进阶之道 用 Rust 打造命令行利器:从零到一实现 mini-grep 解锁Rust代码组织:轻松掌握Package、Crate与Module Rust 所有权:从内存管理到生产力释放 深入解析 Rust 的面向对象编程:特性、实现与设计模式 Rust + Protobuf:从零打造高效键值存储项目 bacon 点燃 Rust:比 cargo-watch 更爽的开发体验 用 Rust 打造微型游戏:从零开始的 Flappy Dragon 开发之旅 函数式编程的Rust之旅:闭包与迭代器的深入解析与实践 探索Rust编程之道:从设计哲学到内存安全的学习笔记 精读《Rust编程之道》:吃透语言精要,彻底搞懂所有权与借用 Rust 避坑指南:搞定数值比较,别再让 0.1 + 0.2 != 0.3 困扰你! 告别 Vec!掌握 Rust bytes 库,解锁零拷贝的真正威力 告别竞态条件:基于 Axum 和 Serde 的 Rust 并发状态管理最佳实践 Rust 异步编程实践:从 Tokio 基础到阻塞任务处理模式 Rust 网络编程实战:用 Tokio 手写一个迷你 TCP 反向代理 (minginx) 保姆级教程:Zsh + Oh My Zsh 终极配置,让你的 Ubuntu 终端效率倍增 不止于后端:Rust 在 Web 开发中的崛起之路 (2024数据解读) Rust核心利器:枚举(Enum)与模式匹配(Match),告别空指针,写出优雅健壮的代码 Rust 错误处理终极指南:从 panic! 到 Result 的优雅之道 想用 Rust 开发游戏?这份超详细的入门教程请收好! 用 Rust 实现 HTTPie:一个现代 CLI 工具的构建过程 Rust 异步实战:从0到1,用 Tokio 打造一个高性能并发聊天室 深入 Rust 核心:彻底搞懂指针、引用与智能指针

Rust 中的 HashMap 实战指南:理解与优化技巧

Rust中的HashMap实战指南:理解与优化技巧在Rust编程中,HashMap是一个强大的键值对数据结构,广泛应用于数据统计、信息存储等场景。在本文中,我们将通过三个实际的代码示例,详细讲解HashMap的基本用法以及如何在真实项目中充分利用它。此外,我们还将探讨Rust的

Rust 中的 HashMap 实战指南:理解与优化技巧

在 Rust 编程中,HashMap 是一个强大的键值对数据结构,广泛应用于数据统计、信息存储等场景。在本文中,我们将通过三个实际的代码示例,详细讲解 HashMap 的基本用法以及如何在真实项目中充分利用它。此外,我们还将探讨 Rust 的所有权系统对 HashMap 的影响,并分享避免常见陷阱的技巧。

本文通过三个 Rust 实战例子,展示了 HashMap 的基本用法及其在实际场景中的应用。我们将从简单的水果篮子示例出发,逐步演示如何使用 HashMap 存储和处理不同数据,并通过添加测试用例来确保代码的正确性。此外,我们还会深入探讨 Rust 所有权系统对 HashMap 使用的影响,尤其是如何避免所有权转移的问题。

实操

示例一:使用 HashMap 存储水果篮子

// hashmaps1.rs
//
// A basket of fruits in the form of a hash map needs to be defined. The key
// represents the name of the fruit and the value represents how many of that
// particular fruit is in the basket. You have to put at least three different
// types of fruits (e.g apple, banana, mango) in the basket and the total count
// of all the fruits should be at least five.
//
// Make me compile and pass the tests!
//
// Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a
// hint.

use std::collections::HashMap;

fn fruit_basket() -> HashMap<String, u32> {
    let mut basket = HashMap::new(); // TODO: declare your hash map here.

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

    // TODO: Put more fruits in your basket here.
    basket.insert(String::from("apple"), 3);
    basket.insert(String::from("mango"), 4);
    basket.insert(String::from("orange"), 5);
    basket
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn at_least_three_types_of_fruits() {
        let basket = fruit_basket();
        assert!(basket.len() >= 3);
    }

    #[test]
    fn at_least_five_fruits() {
        let basket = fruit_basket();
        assert!(basket.values().sum::<u32>() >= 5);
    }
}

在 本例中,我们构建了一个水果篮子,并通过 HashMap 来存储水果种类及其数量。

通过测试,我们验证了篮子中至少有三种水果,并且总数超过五个。

示例二:不重复添加水果

// hashmaps2.rs
//
// We're collecting different fruits to bake a delicious fruit cake. For this,
// we have a basket, which we'll represent in the form of a hash map. The key
// represents the name of each fruit we collect and the value represents how
// many of that particular fruit we have collected. Three types of fruits -
// Apple (4), Mango (2) and Lychee (5) are already in the basket hash map. You
// must add fruit to the basket so that there is at least one of each kind and
// more than 11 in total - we have a lot of mouths to feed. You are not allowed
// to insert any more of these fruits!
//
// Make me pass the tests!
//
// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a
// hint.

use std::collections::HashMap;

#[derive(Hash, PartialEq, Eq)]
enum Fruit {
    Apple,
    Banana,
    Mango,
    Lychee,
    Pineapple,
}

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

    for fruit in fruit_kinds {
        // TODO: Insert new fruits if they are not already present in the
        // basket. Note that you are not allowed to put any type of fruit that's
        // already present!
        *basket.entry(fruit).or_insert(1);
        // 如果水果不在篮子中,则插入数量为1的该水果
        // if !basket.contains_key(&fruit) {
        //     basket.insert(fruit, 1);
        // }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Don't modify this function!
    fn get_fruit_basket() -> HashMap<Fruit, u32> {
        let mut basket = HashMap::<Fruit, u32>::new();
        basket.insert(Fruit::Apple, 4);
        basket.insert(Fruit::Mango, 2);
        basket.insert(Fruit::Lychee, 5);

        basket
    }

    #[test]
    fn test_given_fruits_are_not_modified() {
        let mut basket = get_fruit_basket();
        fruit_basket(&mut basket);
        assert_eq!(*basket.get(&Fruit::Apple).unwrap(), 4);
        assert_eq!(*basket.get(&Fruit::Mango).unwrap(), 2);
        assert_eq!(*basket.get(&Fruit::Lychee).unwrap(), 5);
    }

    #[test]
    fn at_least_five_types_of_fruits() {
        let mut basket = get_fruit_basket();
        fruit_basket(&mut basket);
        let count_fruit_kinds = basket.len();
        assert!(count_fruit_kinds >= 5);
    }

    #[test]
    fn greater_than_eleven_fruits() {
        let mut basket = get_fruit_basket();
        fruit_basket(&mut basket);
        let count = basket.values().sum::<u32>();
        assert!(count > 11);
    }

    #[test]
    fn all_fruit_types_in_basket() {
        let mut basket = get_fruit_basket();
        fruit_basket(&mut basket);
        for amount in basket.values() {
            assert_ne!(amount, &0);
        }
    }
}

在上面的示例代码中,我们通过 HashMap 存储多个水果,但避免重复添加已有的水果种类。

测试用例验证了我们不会修改已存在的水果,并确保总数超过 11 个。

示例三:记录比赛比分

// hashmaps3.rs
//
// A list of scores (one per line) of a soccer match is given. Each line is of
// the form : "<team_1_name>,<team_2_name>,<team_1_goals>,<team_2_goals>"
// Example: England,France,4,2 (England scored 4 goals, France 2).
//
// You have to build a scores table containing the name of the team, goals the
// team scored, and goals the team conceded. One approach to build the scores
// table is to use a Hashmap. The solution is partially written to use a
// Hashmap, complete it to pass the test.
//
// Make me pass the tests!
//
// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a
// hint.

use std::collections::HashMap;

// A structure to store the goal details of a team.
struct Team {
    goals_scored: u8,
    goals_conceded: u8,
}

fn build_scores_table(results: String) -> HashMap<String, Team> {
    // The name of the team is the key and its associated struct is the value.
    let mut scores: HashMap<String, Team> = HashMap::new();

    for r in results.lines() {
        let v: Vec<&str> = r.split(',').collect();
        let team_1_name = v[0].to_string();
        let team_1_score: u8 = v[2].parse().unwrap();
        let team_2_name = v[1].to_string();
        let team_2_score: u8 = v[3].parse().unwrap();
        // TODO: Populate the scores table with details extracted from the
        // current line. Keep in mind that goals scored by team_1
        // will be the number of goals conceded from team_2, and similarly
        // goals scored by team_2 will be the number of goals conceded by
        // team_1.

        // 更新 team_1 的数据
        let team_1 = scores.entry(team_1_name.clone()).or_insert(Team {
            goals_scored: 0,
            goals_conceded: 0,
        });
        team_1.goals_scored += team_1_score;
        team_1.goals_conceded += team_2_score;

        // 更新 team_2 的数据
        let team_2 = scores.entry(team_2_name.clone()).or_insert(Team {
            goals_scored: 0,
            goals_conceded: 0,
        });
        team_2.goals_scored += team_2_score;
        team_2.goals_conceded += team_1_score;
    }
    scores
}

#[cfg(test)]
mod tests {
    use super::*;

    fn get_results() -> String {
        let results = "".to_string()
            + "England,France,4,2\n"
            + "France,Italy,3,1\n"
            + "Poland,Spain,2,0\n"
            + "Germany,England,2,1\n";
        results
    }

    #[test]
    fn build_scores() {
        let scores = build_scores_table(get_results());

        let mut keys: Vec<&String> = scores.keys().collect();
        keys.sort();
        assert_eq!(
            keys,
            vec!["England", "France", "Germany", "Italy", "Poland", "Spain"]
        );
    }

    #[test]
    fn validate_team_score_1() {
        let scores = build_scores_table(get_results());
        let team = scores.get("England").unwrap();
        assert_eq!(team.goals_scored, 5);
        assert_eq!(team.goals_conceded, 4);
    }

    #[test]
    fn validate_team_score_2() {
        let scores = build_scores_table(get_results());
        let team = scores.get("Spain").unwrap();
        assert_eq!(team.goals_scored, 0);
        assert_eq!(team.goals_conceded, 2);
    }
}

本示例展示了 HashMap 在复杂场景中的应用,如记录足球比赛的比分。我们通过 HashMap 将每支球队的得分和失分进行统计。并通过测试来验证比分记录是否正确。

思考

1. 为什么要用 team_1_name.clone()

在 Rust 中,String 是一个拥有所有权的类型,意味着它的值在默认情况下会被移动,而不是复制。如果你直接使用 team_1_name 作为 HashMap 的键,那么当你调用 entry(team_1_name) 时,team_1_name 的所有权会被移动到 entry() 函数中。

之后,如果你还想使用 team_1_name,就无法访问它了,因为所有权已经被移动了。这时你需要通过 clone() 创建一个新的副本(浅拷贝),这样你可以保留原始的 String

使用 .clone() 的目的是避免所有权转移而导致变量不可用。

示例:

let team_1_name = "England".to_string();
// 所有权被移动给 entry(),你不能再访问 team_1_name
scores.entry(team_1_name); 

// 如果你还想用 team_1_name,就要使用 clone():
scores.entry(team_1_name.clone());

如果 team_1_name 是一个 &str(即字符串切片,通常是不可变引用),那么你就不需要 clone(),因为引用类型不涉及所有权的移动问题。

2. 为什么不用结构体直接初始化,而是用累加的方式?

在每场比赛的过程中,某个队伍可能会多次出现,例如:

  • 比赛1:England 对 France
  • 比赛2:Germany 对 England

我们需要在 HashMap 中更新每个队伍的进球和失球信息,而不是每次都覆盖已有数据。因此,我们不能每次都用新的结构体初始化,而是要先检查该队伍是否已经在 HashMap 中存在,然后累加其数据。

这里用的是 entry() 方法,它的作用是:

  • 如果 team_1_name 还没有在 HashMap 中出现,就插入一个新的 Team 结构体,并初始化进球和失球为 0。
  • 如果 team_1_name 已经在 HashMap 中了,那么直接获取它对应的 Team 结构体,并更新其 goals_scoredgoals_conceded 字段。

通过这种方式,每次遇到相同队伍时,不会重新初始化,而是将新的进球和失球数累加到已有数据中。

let team_1 = scores.entry(team_1_name.clone()).or_insert(Team {
    goals_scored: 0,
    goals_conceded: 0,
});

// 累加进球和失球
team_1.goals_scored += team_1_score;
team_1.goals_conceded += team_2_score;

这样就能保证每个队伍的分数在不同比赛中是累积的,而不是被覆盖掉。

思考总结

  • team_1_name.clone() 是为了避免移动所有权导致变量不可用。
  • 累加进球数和失球数 是因为一个队伍可能会出现在多场比赛中,不能每次都重新初始化数据,而是要在已有的基础上进行更新。

这两者结合起来,能确保正确跟踪每个队伍的进球和失球情况。

总结

通过这三个 HashMap 的实战示例,我们不仅掌握了如何高效地使用 HashMap 存储和操作数据,还深入理解了 Rust 的所有权与借用规则在实际开发中的应用。Rust 强调所有权的管理,尤其是在处理复杂数据结构如 HashMap 时,准确掌控所有权的转移和数据的引用关系至关重要,这不仅能够提高代码的效率,还能保障程序的安全性和稳定性。

这些实践展示了 HashMap 在解决实际问题中的强大能力,尤其在需要频繁查找、插入和更新数据的场景中。熟练掌握 HashMap 的使用技巧,将极大提升我们在 Rust 开发中的数据管理效率与程序性能。

参考

点赞 1
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论