Macro hash_map

Source
macro_rules! hash_map {
    () => { ... };
    ( $( $key:expr => $value:expr ),* $(,)? ) => { ... };
}
🔬This is a nightly-only experimental API. (hash_map_macro #144032)
Expand description

Creates a HashMap containing the arguments.

hash_map! allows specifying the entries that make up the HashMap where the key and value are separated by a =>.

The entries are separated by commas with a trailing comma being allowed.

It is semantically equivalent to using repeated HashMap::insert on a newly created hashmap.

hash_map! will attempt to avoid repeated reallocations by using HashMap::with_capacity.

§Examples

#![feature(hash_map_macro)]

let map = hash_map! {
    "key" => "value",
    "key1" => "value1"
};

assert_eq!(map.get("key"), Some(&"value"));
assert_eq!(map.get("key1"), Some(&"value1"));
assert!(map.get("brrrrrrooooommm").is_none());

And with a trailing comma

 #![feature(hash_map_macro)]

 let map = hash_map! {
     "key" => "value", // notice the ,
 };

 assert_eq!(map.get("key"), Some(&"value"));

The key and value are moved into the HashMap.