Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multidimensional array into multidimensional HashMap in Rust

use std::collections::HashMap;

fn main() {
    let tuples = [("outer1", [("inner1", 1), ("inner2", 2), ("inner3", 3)])];
    let m: HashMap<_, _> = tuples.into_iter().collect();
    println!("{:?}", m);
}

This code prints the following: {"outer1": [("inner1", 1), ("inner2", 2), ("inner3", 3)]}

That is a HashMap of strings to an array of tuples. Instead, I want to create a HashMap of the inner layer as well, i.e.: {"outer1": {"inner1": 1, "inner2": 2, "inner3": 3}}

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9ef9dd56592ac820a86d529dba085129

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a clean, idiomatic way to accomplish this?

>Solution :

Map over the entries and turn those into a hashmap as well:

let m: HashMap<_, HashMap<_, _>> =
    tuples
        .into_iter()
        .map(|(key, entries)| (key, entries.into_iter().collect()))
        .collect();

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading