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

如何向HashMap<T, HashMap<T, i32>>中按外层键插入内层HashMap?

嵌套HashMap插入实现方法

针对你需要的HashMap<T, HashMap<T, i32>>结构插入需求,这里提供两种直接的实现方式:

1. 直接构造内层HashMap插入

先创建并初始化好内层的HashMap,再将其作为值插入外层HashMap:

use std::collections::HashMap;

fn main() {
    let x = vec![1, 2];
    let mut map: HashMap<i32, HashMap<i32, i32>> = HashMap::new();
    
    // 初始化内层HashMap,插入目标键值对
    let mut inner_map = HashMap::new();
    inner_map.insert(x[1], 0);
    // 将内层HashMap作为值插入外层
    map.insert(x[0], inner_map);
    
    println!("{:?}", map); // 输出 {1: {2: 0}}
}

2. 使用Entry API(更安全的场景)

如果外层键可能已经存在,不想覆盖原有内层HashMap,推荐用entry+or_insert_with的组合,既能保证外层键不存在时创建新的内层HashMap,又能直接向内层插入数据:

use std::collections::HashMap;

fn main() {
    let x = vec![1, 2];
    let mut map: HashMap<i32, HashMap<i32, i32>> = HashMap::new();
    
    // 外层键不存在则创建新的内层HashMap,随后向内层插入键值对
    map.entry(x[0])
        .or_insert_with(HashMap::new)
        .insert(x[1], 0);
    
    println!("{:?}", map);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:25:25