Skip to content
TheChatArchiveThe Chat Archive
Qwenqwen3-30b-a3b· Alibaba (Qwen)Hugging Face LMArena Human Preference 140K

In Rust I want to make a HashMap of structs. Is there a way I can include multiple…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with o3-2025-04-16’s answer.
  1. User

    In Rust I want to make a HashMap of structs. Is there a way I can include multiple struct types in the same HashMap?

  2. Qwen Assistant

    In Rust, you cannot directly store multiple distinct struct types in a single HashMap because Rust enforces strong static typing. However, you can achieve this by using enums or trait objects to unify the different types into a single, consistent value type. Below are the two primary approaches, along with examples and guidance on when to use each.


    ✅ Option 1: Use an Enum to Wrap Multiple Struct Types

    This is the most straightforward and idiomatic approach in Rust. You define an enum that can hold any of the struct types you want to store, and then use that enum as the value type in your HashMap.

    Example:

    use std::collections::HashMap;
    
    // Define the structs
    struct Person {
        name: String,
    }
    
    struct Company {
        name: String,
    }
    
    // Define an enum to wrap both struct types
    enum Data {
        Person(Person),
        Company(Company),
    }
    
    fn main() {
        let mut map: HashMap<String, Data> = HashMap::new();
    
        let person = Person { name: "Alice".to_string() };
        let company = Company { name: "Acme Corp".to_string() };
    
        map.insert("user".to_string(), Data::Person(person));
        map.insert("org".to_string(), Data::Company(company));
    
        // Accessing values
        if let Some(Data::Person(p)) = map.get("user") {
            println!("Person: {}", p.name);
        }
    
        if let Some(Data::Company(c)) = map.get("org") {
            println!("Company: {}", c.name);
        }
    }
    

    ⚠️ Notes:

    • This approach is type-safe and allows you to pattern match on the different variants.
    • It is more flexible when you need to access specific fields of the structs.
    • No need for dynamic dispatch or boxing.

    ✅ Option 2: Use Trait Objects with Box<dyn Trait>

    If your structs implement a common trait, you can use trait objects to store them in the same HashMap. This is useful when you only need to call methods defined on the trait, not access the internal data directly.

    Example:

    use std::collections::HashMap;
    use std::fmt::Display;
    
    // Define the structs
    struct Person {
        name: String,
    }
    
    struct Company {
        name: String,
    }
    
    // Implement a common trait (e.g., Display)
    impl Display for Person {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "Person: {}", self.name)
        }
    }
    
    impl Display for Company {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "Company: {}", self.name)
        }
    }
    
    fn main() {
        let mut map: HashMap<String, Box<dyn Display>> = HashMap::new();
    
        let person = Person { name: "Alice".to_string() };
        let company = Company { name: "Acme Corp".to_string() };
    
        map.insert("user".to_string(), Box::new(person));
        map.insert("org".to_string(), Box::new(company));
    
        for (key, value) in &map {
            println!("{}: {}", key, value);
        }
    }
    

    ⚠️ Notes:

    • This requires that the structs implement a common trait (like Display, Debug, etc.).
    • You can only call methods defined on the trait, not the struct-specific methods.
    • Trait objects require dynamic dispatch, which may have a small performance cost.
    • The dyn Trait must be 'static, so the structs must not contain non-'static references.

    📌 Choosing Between the Two Approaches

    Use CaseRecommendation
    Need to access specific fields of each struct✅ Use an enum
    Only need to call shared methods (e.g., Display)✅ Use trait objects
    Want maximum flexibility and type safety✅ Use an enum

    Summary

    To include multiple struct types in a single HashMap in Rust:

    • Use an enum if you need to access specific fields or data.
    • Use trait objects (Box<dyn Trait>) if you only need to call shared methods.

    Both approaches are valid and idiomatic in Rust, depending on your use case.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.