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

相关推荐
shimly1234562 小时前
(done) 速通 rustlings(15) 字符串
rust
shimly1234563 小时前
(done) 速通 rustlings(22) 泛型
rust
yezipi耶不耶4 小时前
我在 RTMate 里使用的高并发连接管理利器: DashMap
websocket·rust
初恋叫萱萱9 小时前
深入解析 Rust + LLM 开发:手把手教你写一个 AI 运维助手
运维·人工智能·rust
shimly12345617 小时前
(done) 速通 rustlings(9) 分支跳转
rust
shimly1234561 天前
(done) 速通 rustlings(4) 变量声明
rust
shimly1234561 天前
(done) 速通 rustlings(11) 向量vector及其操作
rust
shimly1234561 天前
(done) 速通 rustlings(3) intro1 println!()
rust
shimly1234561 天前
(done) 速通 rustlings(12) 所有权
rust