How to convert toml-rs Map to std::collections::HashMap [Rust]

Viewed 52

I have the following toml::map::Map object named groups. How can I convert groups to a standard std::collections::HashMap? In other words, I would like to cast toml::map::Map to std::collections::HashMap.

As an added constraint, assume that the keys and values are mutable. This means that the keys may not always be "band" and "mode".

use serde::*;
use std::collections::HashMap;
use toml::value::Value;
use toml::map::Map;

fn main() {
    let v1 =  Value::String("20m".to_string());
    let v2 =  Value::String("40m".to_string());
    let v3 =  Value::String("cw".to_string());
    let v4 =  Value::String("ssb".to_string());

    let band = Value::Array(vec![v1, v2]);
    let mode = Value::Array(vec![v3, v4]);

    let mut g = Map::new();
    g.insert("band".to_string(), band);
    g.insert("mode".to_string(), mode);
    let groups = Some(g);
    dbg!("{:#?}", groups);
}
1 Answers

HashMap::deserialize() can accept a toml::Value::Table. To modify the script above try this:

use serde::*;
use std::collections::HashMap;
use toml::value::Value;
use toml::map::Map;

fn main() {
    let v1 =  Value::String("20m".to_string());
    let v2 =  Value::String("40m".to_string());
    let v3 =  Value::String("cw".to_string());
    let v4 =  Value::String("ssb".to_string());

    let band = Value::Array(vec![v1, v2]);
    let mode = Value::Array(vec![v3, v4]);

    let mut g = Map::new();
    g.insert("band".to_string(), band);
    g.insert("mode".to_string(), mode);
    let res: HashMap<String, Vec<String>> = HashMap::deserialize(toml::Value::Table(g)).unwrap();
    dbg!(res);
}

Rust Playground Run

Related