作者:V体验_数码IT | 来源:互联网 | 2023-05-22 21:19
我用a HashMap
来计算字符串中不同字符的出现次数:
let text = "GATTACA";
let mut counts: HashMap = 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中我会这样做:
counts = { 'A': 0, 'C': 0, 'G': 0, 'T': 0 }
要么
counts = { key: 0 for key in 'ACGT' }
huon..
44
您可以使用迭代器来模拟字典理解,例如
let counts = "ACGT".chars().map(|c| (c, 0_i32)).collect::>();
甚至 for c in "ACGT".chars() { counts.insert(c, 0) }
.
此外,可以编写宏来允许任意值的简明初始化.
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];
.
1> huon..:
您可以使用迭代器来模拟字典理解,例如
let counts = "ACGT".chars().map(|c| (c, 0_i32)).collect::>();
甚至 for c in "ACGT".chars() { counts.insert(c, 0) }
.
此外,可以编写宏来允许任意值的简明初始化.
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];
.
那绝对应该是std!