RRust By Example
advancedMacros

Declarative Macros

Create custom macros with macro_rules!.

Declarative Macros

Create custom macros with macro_rules!.

Difficulty

Advanced

Code

rust
macro_rules! say_hello {
    () => {
        println!("Hello!")
    };
    ($name:expr) => {
        println!("Hello, {}!", $name)
    };
}

macro_rules! vec_of_strings {
    ($($x:expr),*) => {
        vec![$($x.to_string()),*]
    };
}

fn main() {
    say_hello!();
    say_hello!("Rust");

    let names = vec_of_strings!["Alice", "Bob", "Charlie"];
    println!("{:?}", names);
}

Explanation

Declarative macros pattern-match on syntax.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the macros category to build a complete understanding of this topic.

More Macros Examples