You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rust HashMap中按插入索引获取键值对?

解决Rust中按插入顺序访问哈希表元素的问题

标准库的HashMap是无序的,它不会保留键值对的插入顺序,所以你没法直接通过插入顺序获取第二个插入的('c', 2)。要实现需求,有两种常用方案:

方案一:使用indexmap crate的IndexMap

indexmap是一个第三方crate,提供了保留插入顺序的哈希表实现,用法和HashMap基本一致,还支持按索引访问元素。

  1. 先在Cargo.toml中添加依赖:
[dependencies]
indexmap = "2.0"
  1. 代码实现:
use indexmap::IndexMap;

fn main() {
    let mut map: IndexMap<char, u64> = IndexMap::new();
    map.insert('a', 1);
    map.insert('c', 2);
    map.insert('b', 3);

    // 获取第二个插入的元素(索引从0开始,所以用1)
    if let Some((&key, &value)) = map.get_index(1) {
        println!("键:{},值:{}", key, value); // 输出:键:c,值:2
    }
}

方案二:手动维护插入顺序

如果不想引入第三方依赖,可以同时用一个Vec保存插入的键的顺序,搭配HashMap使用:

use std::collections::HashMap;

fn main() {
    let mut map: HashMap<char, u64> = HashMap::new();
    let mut insert_order: Vec<char> = Vec::new();

    // 插入时同时记录顺序
    map.insert('a', 1);
    insert_order.push('a');
    
    map.insert('c', 2);
    insert_order.push('c');
    
    map.insert('b', 3);
    insert_order.push('b');

    // 获取第二个插入的元素
    if let Some(&key) = insert_order.get(1) {
        if let Some(&value) = map.get(&key) {
            println!("键:{},值:{}", key, value); // 输出:键:c,值:2
        }
    }
}

内容的提问来源于stack exchange,提问作者Charles Chiakwa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 15:32:11