多维数组在Rust中转换为多维HashMap

eagi6jfj  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(263)
use std::collections::HashMap;

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

此代码打印以下内容:{"outer1": [("inner1", 1), ("inner2", 2), ("inner3", 3)]}
这是一个字符串到元组数组的HashMap。相反,我想创建一个内层的HashMap,即:{"outer1": {"inner1": 1, "inner2": 2, "inner3": 3}}
Playground:https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9ef9dd56592ac820a86d529dba085129
有没有一个干净的,惯用的方法来完成这一点?

rkue9o1l

rkue9o1l1#

Map条目并将其转换为散列表:

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

Playground

相关问题