utils_soeur/
collections.rs

1/// 快速构建一个[std::collections::HashMap]
2///
3/// ```rust
4/// use utils_soeur::hashmap;
5///
6/// hashmap! {
7///     1 => 'a'
8/// };
9/// ```
10///
11/// with_capacity:
12/// ```
13/// use utils_soeur::hashmap;
14///
15/// hashmap! (2, {
16///     1 => 'a',
17///     2 => 'b'
18/// });
19/// ```
20#[macro_export]
21macro_rules! hashmap {
22    ($capacity:expr, { $($key:expr => $value:expr),* }) => {
23        {
24            let mut _map = std::collections::HashMap::with_capacity($capacity);
25            $( _map.insert($key, $value); )*
26            _map
27        }
28    };
29
30    (capacity = $capacity:expr, { $($key:expr => $value:expr),* }) => {
31        $crate::hashmap!($capacity, { $($key => $value),* })
32    };
33
34    { $($key:expr => $value:expr),* } => {
35        $crate::hashmap!(0, { $($key => $value),* })
36    };
37}
38
39#[test]
40fn test_hashmap() {
41    let mut map = std::collections::HashMap::new();
42    map.insert(1, 2);
43
44    let map2 = hashmap! {
45        1 => 2
46    };
47
48    assert_eq!(map, map2);
49}