Rust — Macros
Declarative macros
macro_rules! say_hello {
() => {
println!("Hello, World!");
};
}
macro_rules! create_function {
($func_name:ident) => {
fn $func_name() {
println!("Function: {}", stringify!($func_name));
}
};
}
create_function!(foo);
create_function!(bar);
fn main() {
say_hello!();
foo();
bar();
}
Macro with parameters
macro_rules! calculate {
(eval $e:expr) => {
{
let val: i64 = $e;
println!("{} = {}", stringify!($e), val);
}
};
}
fn main() {
calculate!(eval 1 + 2);
calculate!(eval 10 * 5);
}
Pattern matching in macros
macro_rules! vector {
($($x:expr),*) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
fn main() {
let v = vector![1, 2, 3, 4, 5];
println!("{:?}", v);
}
Procedural macros
// Custom derive macro
use proc_macro::TokenStream;
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
// Implementation
input
}
Mini Practice
Write Rust code that:
- Creates a basic macro with macro_rules!
- Uses pattern matching in macros
- Creates a macro that generates functions
- Demonstrates macro hygiene
Up Next
In the next lesson, you'll learn about Unsafe Rust — when you need more control.
Related Topics
Frequently Asked Questions about Macros
What is Macros in Rust?
Macros is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Macros?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Macros.
Why is Macros important in Rust?
Macros is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.