Yes—but because a HashMap<K, V> must have a single, concrete value type V, you need a unifying “wrapper” around those different structs.
In practice that wrapper is usually
- An
enum
- A trait object (
Box<dyn MyTrait>)
- A catch-all
Box<dyn Any> (least ergonomic; you down-cast manually)
Below are examples of the two approaches you’ll see 99 % of the time: an enum and a trait object.
- Using an enum (idiomatic & zero-cost dispatch)
use std::collections::HashMap;
#[derive(Debug)]
struct Cat { name: String, lives: u8 }
#[derive(Debug)]
struct Dog { name: String, good_boy: bool }
#[derive(Debug)]
enum Pet {
Cat(Cat),
Dog(Dog),
}
fn main() {
let mut pets: HashMap<&'static str, Pet> = HashMap::new();
pets.insert("whiskers", Pet::Cat(Cat { name: "Whiskers".into(), lives: 9 }));
pets.insert("fido", Pet::Dog(Dog { name: "Fido".into(), good_boy: true }));
// Pattern-match when you read:
if let Some(pet) = pets.get("fido") {
match pet {
Pet::Cat(cat) => println!("Cat named {}", cat.name),
Pet::Dog(dog) => println!("Dog named {}", dog.name),
}
}
}
Pros
• No heap allocation necessary (unless your structs themselves allocate).
• Zero-cost: compiler knows the exact variant at each match.
• Works fine with Copy, Clone, Serialize, etc. via derive on the enum.
Cons
• You must enumerate every possible struct ahead of time.
• Adding a new struct = editing the enum (closed set).
- Using a trait object (open set, dynamic dispatch)
use std::collections::HashMap;
trait Speak {
fn speak(&self);
}
#[derive(Debug)]
struct Cat { name: String }
#[derive(Debug)]
struct Dog { name: String }
impl Speak for Cat {
fn speak(&self) { println!("{} says: meow", self.name); }
}
impl Speak for Dog {
fn speak(&self) { println!("{} says: woof", self.name); }
}
fn main() {
// Box the trait object so everything has the same size.
let mut speakers: HashMap<&'static str, Box<dyn Speak>> = HashMap::new();
speakers.insert("kitty", Box::new(Cat { name: "Kitty".into() }));
speakers.insert("pup", Box::new(Dog { name: "Pup".into() }));
// Call via dynamic dispatch
for (_key, animal) in &speakers {
animal.speak();
}
}
Pros
• Open for extension: any future type can be inserted as long as it impl Speak.
• Call through trait object without needing a match.
Cons
• Each value lives on the heap (Box) and incurs dynamic-dispatch cost (vtable).
• Trait must be object-safe (e.g., no generic methods).
- Catch-all
Box<dyn Any> (rarely recommended)
use std::{any::Any, collections::HashMap};
let mut map: HashMap<&str, Box<dyn Any>> = HashMap::new();
map.insert("num", Box::new(123_i32));
map.insert("text", Box::new(String::from("hello")));
if let Some(any_val) = map.get("num") {
if let Some(num) = any_val.downcast_ref::<i32>() {
println!("got an i32: {num}");
}
}
This gives maximum flexibility but you lose static guarantees; every lookup requires a down-cast that can fail at runtime.
Which one should I use?
• If you have a closed set of types known at compile-time → prefer an enum.
• If you want a pluggable set where new types can come from other crates / plugins → use a trait object (Box<dyn Trait>).
• Only use Any when you really need “store absolutely anything”.
Side notes
• Because keys in HashMap must implement Eq + Hash, ensure your chosen key type does so (String, &'static str, integers, etc. already do).
• If your structs vary wildly in size, boxing in the enum (enum Pet { Cat(Box<Cat>), ... }) can avoid making the enum as large as its biggest variant.
• For multithreaded scenarios use Box<dyn Trait + Send + Sync>.
That’s all there is to it—pick the wrapper style that fits your use-case, and you’re free to mix and match multiple struct types inside a single HashMap. Happy coding!