typestar

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

  1. $( ... ),* matches a comma-separated list.
  2. The body repeats once per captured item.
  3. This is how vec! and hashmap! style macros work.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Macros, step 9 of 12 in Modules, tests & macros.

← Previous Next →