Search code examples
rusthashmapserde-json

Vector in a HashMap


I know how to use, String I know how to use, Vector But I am facing issue to use HashMap

#[derive(Serialize)]
pub struct TestStructs {
    pub ttStrngg: String,
    pub ttVctorr: Vec<String>,
    pub ttHshMpp: HashMap<String, Vec<String>>,
}

Here is what I am trying

Don't have any issues with String

ttStrngg: "Stringgg".to_string(),

Don't have any issues with Vector

ttVctorr: vec!["VecStr1".to_string(), "VecStr2".to_string()],

But do have an issue with HashMap ttHshMpp: "HMK1".to_string(), vec!["K1V1".to_string(), "K1V2".to_string()],

I've shared what I tried and now looking for that missing thing in HashMap

Here is the Rust Playground link to try your own

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=68a35bc3f9afc3be47d9d8219d4a6f2a

And here is the error

    Compiling playground v0.0.1 (/playground)
error: expected one of `,`, `:`, or `}`, found `!`
 --> src/main.rs:9:46
  |
6 |     let ttStrctts = TestStructs {
  |                     ----------- while parsing this struct
...
9 |             ttHshMpp: "HMK1".to_string(), vec!["K1V1".to_string(), "K1V2".to_string()]
  |                                           ---^ expected one of `,`, `:`, or `}`
  |                                           |
  |                                           while parsing this struct field

error[E0308]: mismatched types
 --> src/main.rs:9:23
  |
9 |             ttHshMpp: "HMK1".to_string(), vec!["K1V1".to_string(), "K1V2".to_string()]
  |                       ^^^^^^^^^^^^^^^^^^ expected `HashMap<String, Vec<String>>`, found `String`
  |
  = note: expected struct `HashMap<std::string::String, Vec<std::string::String>>`
             found struct `std::string::String`

Solution

  • We can directly initialise the member with

    ttHshMpp: HashMap::from([("HMK1".to_string(), vec!["K1V1".to_string(), "K1V2".to_string()])]),
    

    See the documentation of HashMap::from().

    The inner () specify each pair (k, v), and the [] denote an array containing these pairs.
    Here, we only have a single pair, then this leads to the ([(...)]) notation which may look weird but is simply a specific form of the general case.