更简洁的 HashMap 初始化 [英] More concise HashMap initialization

查看:20
本文介绍了更简洁的 HashMap 初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 HashMap 来计算字符串中不同字符的出现次数:

I'm using a HashMap to count the occurrences of different characters in a string:

let text = "GATTACA";
let mut counts: HashMap<char, i32> = HashMap::new();
counts.insert('A', 0);
counts.insert('C', 0);
counts.insert('G', 0);
counts.insert('T', 0);

for c in text.chars() {
    match counts.get_mut(&c) {
        Some(x) => *x += 1,
        None => (),
    }
}

是否有更简洁或声明性的方式来初始化 HashMap?例如在 Python 中我会这样做:

Is there a more concise or declarative way to initialize a HashMap? For example in Python I would do:

counts = { 'A': 0, 'C': 0, 'G': 0, 'T': 0 }

counts = { key: 0 for key in 'ACGT' }

推荐答案

您可以使用迭代器来模拟字典理解,例如

You can use iterators to emulate the dictionary comprehension, e.g.

let counts = "ACGT".chars().map(|c| (c, 0_i32)).collect::<HashMap<_, _>>();

甚至 for c in "ACGT".chars() { counts.insert(c, 0) }.

另外,可以编写一个宏来允许对任意值进行简明的初始化.

Also, one can write a macro to allow for concise initialisation of arbitrary values.

macro_rules! hashmap {
    ($( $key: expr => $val: expr ),*) => {{
         let mut map = ::std::collections::HashMap::new();
         $( map.insert($key, $val); )*
         map
    }}
}

let counts = hashmap!['A' => 一样使用0, 'C' =>0, 'G' =>0, 'T' =>0];.

这篇关于更简洁的 HashMap 初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆