More concise HashMap initialization

后端 未结 3 839
滥情空心
滥情空心 2020-12-24 01:30

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

let text = \"GATTACA\";
let mut counts: HashMap

        
3条回答
  •  隐瞒了意图╮
    2020-12-24 02:20

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

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

    or even 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
        }}
    }
    

    used like let counts = hashmap!['A' => 0, 'C' => 0, 'G' => 0, 'T' => 0];.

提交回复
热议问题