Rust

macro_rules! — Simple Declarative Macros

admin by @admin ADMIN
18h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Declarative macros let you write functions that take token trees instead of values. Great for boilerplate reduction; cleaner than copy-paste, simpler than proc macros.
Rust
Raw
// Generate a Vec inline (very similar to vec!)
macro_rules! my_vec {
    () => (Vec::new());
    ($($x:expr),+ $(,)?) => {{
        let mut v = Vec::new();
        $( v.push($x); )+
        v
    }};
}

// HashMap literal — like vec! but for maps
macro_rules! hashmap {
    ( $($k:expr => $v:expr),* $(,)? ) => {{
        let mut m = std::collections::HashMap::new();
        $( m.insert($k, $v); )*
        m
    }};
}

// Repeated assert! with descriptive labels
macro_rules! check {
    ( $($name:literal: $cond:expr),+ $(,)? ) => {
        $( assert!($cond, "check '{}' failed", $name); )+
    };
}

fn main() {
    let v = my_vec![1, 2, 3, 4];
    let m = hashmap!{ "a" => 1, "b" => 2 };
    println!("{v:?} {m:?}");
    check!(
        "positive" : v.iter().all(|&x| x > 0),
        "size"     : v.len() == 4,
    );
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.