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

This example demonstrates how to use declarative macros in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

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