Search⌘ K
AI Features

Macros

Explore Rust macros, a powerful compile-time metaprogramming tool that helps reduce code duplication. Understand macro syntax, usage scenarios, and how to apply macros effectively to create scalable and maintainable web applications in Rust.

Introduction to macros

Macros are the Rust metaprogramming feature that creates code in compile-time. Through this, we can save duplication, but we need to be careful because we could make a mess.

Macros are called using a ! in the end. We’ve been using a macro called println! to print text to the standard output.

Rust 1.40.0
macro_rules! says_hi {
() => {
{
println!("Hello World!");
}
};
}
fn main() {
says_hi!();
}

The above code shows a simple macro to print a message. When we want to create a macro, we need to start with macro_rules! followed ...