Macros with repetition in Rust
Repetition captures a list, so one macro builds a whole collection.
use std::collections::HashMap;
macro_rules! table {
($($key:expr => $value:expr),* $(,)?) => {{
let mut map = HashMap::new();
$(map.insert($key, $value);)*
map
}};
}
macro_rules! log_all {
($($line:expr);*) => {
$(println!("[log] {}", $line);)*
};
}
fn main() {
let tours = table! {
"rust" => 11,
"python" => 6,
};
println!("{}", tours["rust"]);
log_all!("started"; "finished");
}
How it works
$( ... ),*matches a comma-separated list.- The body repeats once per captured item.
- This is how
vec!andhashmap!style macros work.
Keywords and builtins used here
exprfnletmainmutuse
The run, in numbers
- Lines
- 25
- Characters to type
- 384
- Tokens
- 142
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 77 seconds.
Step 3 of 3 in Macros, step 9 of 12 in Modules, tests & macros.