Code Example Template
let keys = vec![1, 2, 3];
println!("Key count: {}", keys.len());

Deep-Dive System Documentation

Declarative Macros: Metaprogramming

A Declarative Macro (macro_rules!) allows you to write code that generates other code at compile time. It acts like a high-powered match statement for raw Rust tokens.

Ubiquitous Standard Macros

You've likely used macros continuously:

  • println!("msg"): Expands to system print commands.
  • vec![1, 2, 3]: Expands to allocating dynamic vectors.
  • format!("x: {}", x): Expands to string layout formatting.

Writing a Custom Macro

Macros match tokens using pattern variables prefixed with $:

macro_rules! register_shortcuts {
    ( $( $key:expr => $action:expr ),* ) => {
        {
            let mut map = std::collections::HashMap::new();
            $(
                map.insert($key, $action);
            )*
            map
        }
    };
}

// Expands to inserting multiple items into a HashMap automatically!
let bindings = register_shortcuts!(
    0x41 => "OpenChrome",
    0x42 => "CloseActive"
);

Performance Metrics

  • Cost: Macros compile directly into standard inline Rust statements. There is absolutely no runtime overhead, keeping performance optimal.

Quick Reference Guide

macro_rules! my_macro { () => {} }