HashMap Lookup With Borrowed Keys
Query String-keyed maps through borrowed &str keys because Borrow lets get, get_mut and contains_key accept them, avoiding a to_string allocation per lookup.
Code
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert("widget".to_string(), 12);
stock.insert("gadget".to_string(), 5);
// 键是 String,查询却可以直接用 &str:Borrow<str> 免分配
println!("widget: {:?}", stock.get("widget"));
println!("missing: {:?}", stock.get("nonsense"));
println!("has gadget: {}", stock.contains_key("gadget"));
// get_key_value 一次拿回借用键与值,不必 clone 键
if let Some((key, count)) = stock.get_key_value("widget") {
println!("key {key} len {} count {count}", key.len());
}
// entry 需要所有权:只有插入路径才构造 String 键
let hits = ["widget", "widget", "nonsense"];
for hit in hits {
stock.entry(hit.to_string()).or_insert(0);
*stock.get_mut(hit).expect("just inserted") += 1;
}
println!("widget now: {:?}", stock.get("widget"));
println!("nonsense now: {:?}", stock.get("nonsense"));
}How it works
Count the function main as the entire surface area of HashMap Lookup With Borrowed Keys.
Repetition is confined to for hit in hits — the rest of the file is straight-line.
Using it
The run emits 6 labeled sections — widget:, missing:, has gadget:, key, widget now:, nonsense now: — one per step.
Key statements
if let Some((key, count)) = stock.get_key_value("widget") {
println!("key {key} len {} count {count}", key.len());
}
Interactive Tools for This Topic
FAQ
- What does HashMap Lookup With Borrowed Keys print when run?
- No setup needed: run the file and look for labeled lines like `widget:`, `missing:`, `has gadget:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.