Write a hashmap! macro that builds a HashMap from key => value pairs
Write a declarative macro hashmap! that builds a HashMap from pairs written as key => value, the way vec! builds a vector from a list.
Constraints:
hashmap! {}returns an empty map.- Any number of pairs, separated by commas; a trailing comma after the last pair is allowed.
- Keys and values are arbitrary expressions, not only literals.
- The program must compile without warnings. Do not change
main. - Name the fragment specifiers and repetition operators you used.
use std::collections::HashMap;
macro_rules! hashmap {
// your code here
}
fn main() {
let empty: HashMap<&str, i32> = hashmap! {};
let ages = hashmap! {
"ann" => 31,
"bob" => 27,
};
let mut keys: Vec<_> = ages.keys().copied().collect();
keys.sort();
println!("{} {:?} {}", empty.len(), keys, ages["bob"]); // 0 ["ann", "bob"] 27
}Write the implementation.
Do not add extra use lines unless the task says so explicitly.
Two rules: () => { HashMap::new() } and ($($k:expr => $v:expr),+ $(,)?), whose block makes a map, repeats map.insert($k, $v); with $( … )+ and returns it. expr takes a whole expression; $(,)? allows a trailing comma.
- Using single braces, so an expansion that starts with
letfails in expression position withexpected expression, found `let` statement - Leaving out
$(,)?, so a trailing comma after the last pair ends inunexpected end of macro invocation - Using
$koutside its$( … )group, which rustc rejects as still repeating at this depth
- How would you make
hashmap!preallocate capacity by counting the pairs at compile time? - Why does rustc allow only
=>,,or;right after anexprfragment?
The solution is two rules. The first catches the empty call and returns HashMap::new() right away. The second describes the repetition: $( … ),+ is one or more pairs separated by commas, and $(,)? is an optional trailing comma.
use std::collections::HashMap;
macro_rules! hashmap {
() => { HashMap::new() };
($($k:expr => $v:expr),+ $(,)?) => {{
let mut map = HashMap::new();
$( map.insert($k, $v); )+
map
}};
}
fn main() {
let empty: HashMap<&str, i32> = hashmap! {};
let ages = hashmap! {
"ann" => 31,
"bob" => 27,
};
let mut keys: Vec<_> = ages.keys().copied().collect();
keys.sort();
println!("{} {:?} {}", empty.len(), keys, ages["bob"]); // 0 ["ann", "bob"] 27
}The fragments and operators used:
$k:expr,$v:expr— theexprfragment captures a whole expression, so a key can be"ann",name.clone()ori + 1. After anexprrustc allows only=>,,or;— the=>separator qualifies.$( … ),+— repetition one or more times, separated by commas;*would mean "zero or more".$(,)?— a "zero or one" repetition with no separator: this is what accepts a trailing comma. Without it the call{ "ann" => 31, }ends inunexpected end of macro invocation.$( map.insert($k, $v); )+— in the expansion the group repeats once per matched pair.$kand$vmay appear only inside such a group: outside it rustc answersvariable `k` is still repeating at this depth.
The double braces make the expansion a single block expression: the outer pair belongs to the rule, the inner one to the block. With a single pair the expansion would start with let, and in expression position the build would fail with expected expression, found `let` statement. The separate rule for the empty call keeps the build clean: with * instead of +, the empty call would produce a let mut map that nothing changes, and an unused_mut warning. The call's brackets — (), [] or {} — are interchangeable; braces are the convention for a map.