Search code examples
stringrustsplithashmap

split String twice and put it in a HashMap


I have a String atp.Status="draft";pureMM.maxOccurs="1";pureMM.minOccurs="1";xml.attribute="true" and want to split it twice and insert it into a HashMap. For the first split I use ; and for the second =. It should look like this.

appinfo {
     atp.Status: "draft",
     pureMM.maxOccurs: "1",
     pureMM.minOccurs: "1",
     xml.attribute: "true",
}

This is my code:

let mut appinfo: HashMap<String,String> = HashMap::new();
let text = r#"atp.Status="draft";pureMM.maxOccurs="1";pureMM.minOccurs="1";xml.attribute="true""#;
appinfo = HashMap::from_iter(text.split(";").map(|a|a.split_once("=").unwrap()));

I get:

   = note: expected struct `HashMap<String, String, RandomState>`
              found struct `HashMap<&str, &str, _>`

I have already tried all possible variants and combinations in map and outside with to_string() , into_iter() or collect(). My only working solution was to change the type of HashMap to <&str, &str> but I don't want that. How can I turn the two string splices into normal strings?


Solution

  • Just use to_string() on both parts of the split_once:

    let text = r#"atp.Status="draft";pureMM.maxOccurs="1";pureMM.minOccurs="1";xml.attribute="true""#;
    let appinfo = HashMap::from_iter(text.split(";").map(|a| {
        let (key, value) = a.split_once("=").unwrap();
        (key.to_string(), value.to_string())
    }));