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

Rust中如何用(&str, &str)高效查询键为(String, String)的HashMap?

可以直接查询,无需转换为String

完全可以直接使用(&str, &str)类型的数据查询键为(String, String)的HashMap,不需要先把&str转换成String。

核心原因

Rust标准库的HashMap::get方法支持借用查询机制:

  • String原生实现了Borrow<str>,意味着String可以被无成本借用为str;
  • 元组(T1, T2)会自动实现Borrow<(Q1, Q2)>,只要元组内每个元素T1满足Borrow<Q1>、T2满足Borrow<Q2>。

因此(String, String)可以被借用为(str, str),而(&str, &str)能隐式转换为&(str, str),刚好匹配get方法的参数要求,全程不会产生内存分配。

代码示例

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    // 插入(String, String)类型的键值对
    map.insert(("name".to_string(), "age".to_string()), 25);
    
    // 直接用(&str, &str)执行查询
    let result = map.get(&("name", "age"));
    println!("查询结果: {:?}", result); // 输出 Some(25)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:52:08