Rust中基于字符串枚举索引实现HashMap查找映射的问题
Rust HashMap查找错误:Borrow未实现问题
问题背景
你尝试遍历字符串的字符索引,将索引+1作为HashMap的键查找对应权重值,但代码报错:
error[E0277]: the trait bound `&str: Borrow<String>` is not satisfied
你疑惑明明用了to_string()转换索引为字符串,为什么还是出错。
错误根源
你创建的HashMap键类型是&str(字符串字面量默认类型),而HashMap::get方法要求传入的参数必须满足K: Borrow<Q>(K是HashMap的键类型,Q是参数的类型)。这里你传入的&(i+1).to_string()是&String类型,而&str并没有实现Borrow<String> trait——Rust中只有String可以借用为str,反过来不成立,这就是报错的原因。
三种修复方案
方案1:将HashMap的键改为String类型
把创建HashMap时的所有字符串字面量转为String,让键类型和查找参数的类型统一:
use std::collections::HashMap; fn main() { let weight = HashMap::from([ ("1".to_string(), 8), ("2".to_string(), 7), ("3".to_string(), 6), ("4".to_string(), 5), ("5".to_string(), 4), ("6".to_string(), 3), ("7".to_string(), 2), ("8".to_string(), 1), ("9".to_string(), 0), ("10".to_string(), 9), ("11".to_string(), 8), ("12".to_string(), 7), ("13".to_string(), 6), ("14".to_string(), 5), ("15".to_string(), 4), ("16".to_string(), 3), ("17".to_string(), 2) ]); let s = String::from("Hello World"); let weights: Vec<_> = s.chars() .enumerate() .map(|(i, _)| weight.get(&(i+1).to_string()).unwrap_or(&0)) .collect(); dbg!(weights); }
方案2:直接使用&str类型查找
不修改HashMap的键类型,而是将索引转换为&str类型查找。Rust会自动处理format!生成的临时字符串生命周期:
use std::collections::HashMap; fn main() { let weight = HashMap::from([ ("1", 8), ("2", 7), ("3", 6), ("4", 5), ("5", 4), ("6", 3), ("7", 2), ("8", 1), ("9", 0), ("10", 9), ("11", 8), ("12", 7), ("13", 6), ("14", 5), ("15", 4), ("16", 3), ("17", 2) ]); let s = String::from("Hello World"); let weights: Vec<_> = s.chars() .enumerate() .map(|(i, _)| weight.get(&format!("{}", i+1)).unwrap_or(&0)) .collect(); dbg!(weights); }
方案3:改用整数作为HashMap的键(推荐)
你的键本质是数字,完全可以抛弃字符串类型,直接用整数作为键,既避免字符串转换开销,又消除类型匹配问题:
use std::collections::HashMap; fn main() { let weight = HashMap::from([ (1, 8), (2, 7), (3, 6), (4, 5), (5, 4), (6, 3), (7, 2), (8, 1), (9, 0), (10, 9), (11, 8), (12, 7), (13, 6), (14, 5), (15, 4), (16, 3), (17, 2) ]); let s = String::from("Hello World"); let weights: Vec<_> = s.chars() .enumerate() .map(|(i, _)| weight.get(&(i+1)).unwrap_or(&0)) .collect(); dbg!(weights); }
总结
核心问题是键类型与查找参数类型不匹配导致的Borrow trait不满足。最简洁高效的方式是改用整数作为键,如果必须使用字符串键,统一键和查找参数的类型即可解决问题。
内容的提问来源于stack exchange,提问作者Coldchain9
相关产品推荐
相关产品推荐

