On this page
  1. macro_rules
  2. Availability
  3. Syntax & Overview
  4. Notes & Pitfalls
  5. Example

macro_rules

Prev: unsafe | Up: builtins | Next: try_macro
Rel: builtins, Ownership, Borrowing & Lifetimes
Ref: Rust Docs — macro_rules
Tags: #public #prog #rust #builtins #tier/specialized


Availability

Built-in / Prelude (Declarative Macro) — available with zero use imports.

Syntax & Overview

macro_rules! name { ($x:expr) => { ... }; }

Hygienic token-tree macro system for compile-time code generation without runtime overhead.

Notes & Pitfalls

Example

macro_rules! map_of {
    ($($k:expr => $v:expr),* $(,)?) => {{
        let mut m = std::collections::HashMap::new();
        $(m.insert($k, $v);)*
        m
    }};
}

fn main() {
    let scores = map_of!["ada" => 100, "grace" => 99];
    assert_eq!(scores["ada"], 100);
}

Linked from

Related notes