HashMap 中的向量

问题描述 投票:0回答:1

我知道如何使用,String 我知道如何使用,Vector 但我在使用 HashMap

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

这就是我正在尝试的

String

没有任何问题

ttStrngg: "Stringgg".to_string()
,

Vector

没有任何问题

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

但是 HashMap 有问题

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

我已经分享了我尝试过的内容,现在正在寻找 HashMap 中丢失的东西

这里是 Rust Playground 链接,您可以尝试自己的

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

这是错误

    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`
rust hashmap serde-json
1个回答
0
投票

我们可以直接初始化成员

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

请参阅 HashMap::from()

文档。

© www.soinside.com 2019 - 2024. All rights reserved.