In Rust, how do you write a macro_rules! hashmap! literal macro that accepts key => value pairs with an optional trailing comma?
answer
- one repetition binds two metavariables
- separator comma, star operator
- question mark for the last comma
- double braces make a block expression
basics
~10 sMatch $($key:expr => $value:expr),* $(,)? and transcribe a block that creates a HashMap, repeats map.insert($key, $value); once per pair, and returns the map. The inner braces make the expansion one block expression.
solid answer
~40 sThe matcher `($($key:expr => $value:expr),* $(,)?)` repeats a key expression, a literal `=>` and a value expression, separated by commas, zero or more times (`*`), then accepts an optional trailing comma (`?` takes no separator). The transcriber is `{{ let mut map = ::std::collections::HashMap::new(); $( map.insert($key, $value); )* map }}`: the outer braces only delimit the transcriber, and the inner ones make the expansion a single block expression, so `let ports = hashmap!{ "http" => 80 };` works. `$key` and `$value` sit inside one `$( )*` in the transcriber, at the same depth as in the matcher, so rustc emits one `insert` per pair; writing them outside a repetition fails with "variable `key` is still repeating at this depth". `=>` is allowed after an `expr` fragment; `:` is not.
code
rust · 22 linesuse std::collections::HashMap;
macro_rules! hashmap {
($($key:expr => $value:expr),* $(,)?) => {{
#[allow(unused_mut)]
let mut map = ::std::collections::HashMap::new();
$( map.insert($key, $value); )*
map
}};
}
fn main() {
let empty: HashMap<&str, u16> = hashmap!();
let ports = hashmap! {
"http" => 80,
"https" => 443,
};
let one = hashmap!["ssh" => 22];
let mut keys: Vec<_> = ports.keys().copied().collect();
keys.sort();
println!("{} {keys:?} {}", empty.len(), one["ssh"]);
}go deeper
Recognise the parts of a macro_rules! rule: the matcher, the transcriber, a $name:expr metavariable and a repetition. Be able to read hashmap! and say what one call expands to.
Write the macro from scratch: the $( ),* repetition with two metavariables, $(,)? for the trailing comma, the double braces that make a block expression, and the same-depth rule for transcribing.
Review a team's literal macros for the classic slips: single braces, a $(,)? missing, a forbidden separator after expr, and an empty call that needs a type annotation or a separate arm.
Decide whether a literal macro earns its keep next to HashMap::from with an array of pairs, and keep any macro's syntax small and documented, because every arm becomes part of the crate's API.
## The goal A **literal macro** lets a caller write a map the way they write an array: `hashmap!{ "http" => 80, "https" => 443 }`. In Rust that is a job for a **declarative macro** defined with `macro_rules!`, because the number of pairs varies from call to call and a function has a fixed parameter list. ## The matcher ```rust macro_rules! hashmap { ($($key:expr => $value:expr),* $(,)?) => {{ #[allow(unused_mut)] let mut map = ::std::collections::HashMap::new(); $( map.insert($key, $value); )* map }}; } ``` Read the matcher left to right: - **`$( ... ),*`** is a **repetition**: the tokens inside match zero or more times, with a comma as the **separator** between occurrences. - **`$key:expr`** binds each key to the **metavariable** `key`, using the `expr` **fragment specifier**, which accepts any Rust expression: a literal, a variable, a call. - **`=>`** is a literal token the caller must write between key and value. - **`$value:expr`** binds each value. - **`$(,)?`** accepts one optional trailing comma. The Reference says `?` means zero or one occurrence and cannot take a separator. The repetition operators: | Operator | Meaning | Effect on `hashmap!` | |---|---|---| | `*` | any number, including zero | `hashmap!{}` matches and yields an empty map | | `+` | one or more | `hashmap!{}` would fail to match | | `?` | zero or one, no separator | used only for the trailing comma | The choice of `=>` is not cosmetic. An `expr` fragment may only be followed by `=>`, `,` or `;`, so `$key:expr : $value:expr` is rejected at the definition. ## The transcriber Three rules decide whether the expansion is valid. 1. **Same depth.** A metavariable must appear in the transcriber inside the same number and nesting of repetitions as in the matcher. `$( map.insert($key, $value); )*` repeats once per matched pair. Writing `map.insert($key, $value);` outside any `$( )*` makes rustc 1.99.1 report "variable `key` is still repeating at this depth". 2. **Equal counts.** Every metavariable inside one transcriber repetition must have been bound the same number of times. Here `key` and `value` always are, because they come from the same matcher repetition. 3. **One expression.** The outer delimiters of a transcriber are not part of the output. With single braces, `let m = hashmap!{"a" => 1};` expands to bare statements in expression position, and rustc reports "expected expression, found `let` statement". The second pair of braces makes the output one **block expression** whose value is the final `map`. Two smaller choices: - The full path `::std::collections::HashMap` means callers need no `use` for the map type (path resolution inside expansions is covered in the lesson on macro hygiene and scope). - Each `$key` and `$value` appears once in the output, so each argument expression is evaluated exactly once, in the order written. - With zero pairs nothing mutates `map`, and rustc warns "variable does not need to be mutable" when expanding `hashmap!{}`; `#[allow(unused_mut)]` on the `let` keeps the empty call quiet. ## Calling it The outer delimiters of an invocation are interchangeable: `hashmap!{...}`, `hashmap![...]` and `hashmap!(...)` all reach the same rules. The key and value types come from inference, so an empty `hashmap!{}` needs an annotation such as `let m: HashMap<&str, u16> = hashmap!{};`. | Invocation | Result | |---|---| | `hashmap!{ "http" => 80, "https" => 443 }` | two entries | | `hashmap!{ "http" => 80, }` | one entry; `$(,)?` takes the comma | | `hashmap!{}` | empty map, needs a type annotation | | `hashmap!{ "http": 80 }` | error: no rules expected `:` | ## Does the standard library need this? Not for constant data: `HashMap::from([("http", 80), ("https", 443)])` builds a map from an array of pairs through `From<[(K, V); N]>`. A literal macro still earns its place when the team wants `=>` syntax, a `with_capacity` sized to the entry count, or the same shape across several map types. The arms of a declarative macro are cheap to write, but every arm is API, so keep the syntax small: one pair form and a trailing comma cover nearly every call site.
- How would you size the map with with_capacity from the number of pairs?Count the keys at expansion time. A common non-recursive trick maps each `$key` to `()` through an internal helper rule and takes `<[()]>::len(&[...])` of the resulting array, a length known at compile time. A recursive counting rule also works but is limited by the crate's recursion limit.
- Why does the matcher use `*` rather than `+` for the pairs?`*` lets `hashmap!{}` match and produce an empty map, mirroring `vec![]`. With `+`, an empty call matches no rule unless you add a separate `()` arm. Either design works; what matters is that the empty case is deliberate and that callers annotate the map type, since there are no entries to infer it from.
- The trailing comma can be written as $(,),? with a separator
- Single braces around the transcriber already make it one expression
- Using $key outside the repetition inserts only the first pair
- A colon between key and value works the same as =>
- hashmap! must be invoked with braces because it builds a block