【Rust】自定义键类型

环境

  • Rust 1.56.1
  • VSCode 1.61.2

概念

参考:https://doc.rust-lang.org/stable/rust-by-example/std/hash/alt_key_types.html

示例

main.rs

use std::collections::HashMap;

#[derive(PartialEq, Eq, Hash)]
struct Account<'a> {
    username: &'a str,
    password: &'a str,
}

type Accounts<'a> = HashMap<Account<'a>, &'a str>;
fn try_logon(accounts: &Accounts, username: &str, password: &str) {
    println!("Username: {}", username);
    println!("Password: {}", password);
    println!("Attempting logon...");

    let logon = Account { username, password };

    match accounts.get(&logon) {
        Some(age) => {
            println!("Successful logon!");
            println!("Age: {}", age);
        }
        _ => println!("Login failed!"),
    }
}

fn main() {
    let mut accounts = HashMap::new();

    let account = Account {
        username: "j.everyman",
        password: "password123",
    };

    accounts.insert(account, "44");

    try_logon(&accounts, "j.everyman", "psasword123");

    try_logon(&accounts, "j.everyman", "password123");
}

总结

了解了 Rust 中,自定义 HashMap 的键。

附录

posted @   jiangbo4444  阅读(124)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示