typestar

macro_rules! in Rust

A declarative macro matches syntax patterns and expands to code.

macro_rules! square {
    ($n:expr) => {
        $n * $n
    };
}

macro_rules! named_total {
    ($label:ident : $($value:expr),+) => {{
        let total = 0 $(+ $value)+;
        format!("{} = {}", stringify!($label), total)
    }};
}

fn main() {
    println!("{}", square!(7));
    println!("{}", square!(1.5));
    println!("{}", named_total!(stars: 3, 2, 1));
}

How it works

  1. $name:expr captures an expression, :ident a name.
  2. Each rule is a pattern and the tokens it expands into.
  3. #[macro_export] makes it visible outside the crate.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
316
Tokens
115
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 63 seconds.

Type this snippet

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

← Previous Next →