Learn Before
Code

Example of macro_rules! - Rust Programming

// Define a simple macro named `say_hello` // that takes a name as an argument. macro_rules! say_hello { ($name:expr) => { println!("Hello, {}!", $name); }; } // Define a macro named `create_map` // that takes key-value pairs and creates a HashMap. macro_rules! create_map { ($($key:expr => $value:expr),*) => {{ use std::collections::HashMap; let mut map = HashMap::new(); $( map.insert($key, $value); )* map }}; } fn main() { // Use the `say_hello` macro. say_hello!("Alice"); say_hello!("Bob"); // Use the `create_map` macro. let map = create_map! { "one" => 1, "two" => 2, "three" => 3 }; println!("The created map is: {:?}", map); }

0

1

Updated 2023-04-20

Tags

Object-Oriented Programming

Programming Language Paradigms

General programming languages

Computing Sciences