map!() { /* proc-macro */ }
Expand description
Creates any map-like collection that implements FromIterator<(K, V)>
.
It automatically converts each key and value to the target type using Into
.
This way you can write a map of String
s without the need to call .to_owned()
or .to_string()
on every string literal:
let map: HashMap<String, String> = bon::map! {
"key1": "value1",
format!("key{}", 2): "value2",
"key3": format!("value{}", 3),
};
There is no separate variant for BTreeMap
and HashMap
. Instead, you
should annotate the return type of this macro with the desired type or make
sure the compiler can infer the collection type from other context.
§Compile errors
The macro conservatively rejects duplicate keys in the map with a compile error. This check works for very simple expressions that involve only literal values.
ⓘ
let map: HashMap<String, String> = bon::map! {
"key1": "value1",
"key2": "value2"
"key1": "value3", // compile error: `duplicate key in the map`
};