RRust By Example
advancedMacros

DSL with Macros

Build domain-specific languages using macros.

DSL with Macros

Build domain-specific languages using macros.

Difficulty

Advanced

Code

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

macro_rules! vec2d {
    ($( $( $x:expr ),* );* $(;)?) => {
        vec![ $( vec![ $($x),* ] ),* ]
    };
}

fn main() {
    let scores = hash_map! {
        "Alice" => 95,
        "Bob" => 87,
        "Charlie" => 92,
    };
    println!("{:?}", scores);

    let matrix = vec2d![
        1, 2, 3;
        4, 5, 6;
        7, 8, 9
    ];
    println!("{:?}", matrix);
}

Explanation

Macros can create domain-specific languages.

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