HashMap with lookup by key variant that has references?
โ Rust ๐ 2026-04-07 ๐ค surdeus ๐๏ธ 6Say I want to create a cache using a HashMap. My keys are structs that contain a font name and size, something like:
#[derive(Hash, Eq, PartialEq, Debug)]
struct FontKey {
font_name: String,
font_size: NotNan<f32>
}
I don't want to have to allocate that String to look something up. For a lookup, I'd prefer something like:
struct FontKey2 { font_name: &'a str, font_size: NotNan<f32> }
But I canโt put those in my HashMap field. I thought maybe I could Borrow, but I guess not. Donโt see how to fill in the todo!() here. (playground link).
Is there a way to do this? Another path: maybe I can intern the font names and use something like a struct FontNameId(u32) in the cache keys.
use std::collections::HashMap;
use std::borrow::Borrow;
#[derive(Eq, PartialEq, Hash, Debug)]
struct Key {
font_name: String,
font_size: u32,
}
#[derive(Eq, PartialEq, Hash, Debug)]
struct Key2<'a> {
font_name: &'a str,
font_size: u32,
}
impl<'a> Borrow<Key2<'a>> for Key {
fn borrow(&self) -> &Key2<'a> {
todo!()
}
}
fn main() {
let mut cache: HashMap<Key, i32> = HashMap::new();
let font_name: String = "Roboto".to_owned();
cache.insert(Key { font_name: font_name.clone(), font_size: 14 }, 123);
let k2 = Key2 { font_name: font_name.as_str(), font_size: 14 };
let val = cache.get(&k2);
println!("val = {:?}", val);
}
5 posts - 4 participants
๐ท๏ธ Rust_feed