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

如何从带默认值的HashMap中获取元素的引用?

优雅实现HashMap获取默认空Vec的方法

你遇到的问题是临时创建的vec![]会被立即销毁,导致返回的引用悬空。除了临时变量的写法,还有以下几种更优雅的实现方式:

1. 使用标准库std::sync::Lazy(Rust 1.70+)

利用懒加载的静态全局空Vec,其生命周期为'static,可以安全地作为默认返回值:

use std::collections::HashMap;
use std::sync::Lazy;

// 懒初始化全局空Vec,仅在首次使用时创建
static EMPTY_VEC: Lazy<Vec<i32>> = Lazy::new(Vec::new);

fn get_item_with_default(map: &HashMap<&str, Vec<i32>>, key: &str) -> &Vec<i32> {
    map.get(key).unwrap_or(&EMPTY_VEC)
}

2. 使用lazy_static crate(兼容旧版Rust)

如果你的Rust版本低于1.70,可以使用社区维护的lazy_static crate实现同样的懒加载效果:

use lazy_static::lazy_static;
use std::collections::HashMap;

lazy_static! {
    static ref EMPTY_VEC: Vec<i32> = Vec::new();
}

fn get_item_with_default(map: &HashMap<&str, Vec<i32>>, key: &str) -> &Vec<i32> {
    map.get(key).unwrap_or(&*EMPTY_VEC)
}

需要在Cargo.toml中添加依赖:

[dependencies]
lazy_static = "1.4"

3. 调整返回类型为Option<&Vec<i32>>(更符合Rust idiom)

如果业务场景允许,直接返回Option让调用者处理缺失的情况,是更地道的Rust写法:

use std::collections::HashMap;

fn get_item_with_default(map: &HashMap<&str, Vec<i32>>, key: &str) -> Option<&Vec<i32>> {
    map.get(key)
}

调用者可以通过unwrap_or_default()或match来处理默认情况,比如:

let item = get_item_with_default(&map, "key").unwrap_or(&vec![]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:42:38