本文介绍了更简洁的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初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 15:33