Rust Macros — Declarative Macros with macro_rules! and Procedural Macros
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Rust Macros. We cover key concepts, practical examples, and best practices to help you master this topic.
Rust macros include declarative macro_rules! for pattern-based Code Generation and procedural macros for custom derive, attribute, and function-like macros.
What You'll Learn
- macro_rules! basics
- Pattern matching in macros
- Repetition in macros
- Procedural macros overview
Why It Matters
Macros reduce boilerplate. DodaZIP uses macros for error handling patterns. Serde's derive macros are procedural macros.
Real-World Use
Code generation, boilerplate reduction, DSL creation, test utilities.
// Declarative macro
macro_rules! create_function {
($func_name:ident) => {
fn $func_name() {
println!("Called {}", stringify!($func_name));
}
};
}
create_function!(foo);
create_function!(bar);
// Macro with repetition
macro_rules! vec_of_strings {
($($x:expr),*) => {
{
let mut v = Vec::new();
$(v.push($x.to_string());)*
v
}
};
}
macro_rules! assert_equal {
($left:expr, $right:expr) => {
assert_eq!($left, $right, "{} != {}",
stringify!($left), stringify!($right))
};
}
// Macro for building
macro_rules! hashmap {
($($key:expr => $value:expr),* $(,)?) => {
{
let mut map = std::collections::HashMap::new();
$(map.insert($key, $value);)*
map
}
};
}
fn main() {
foo();
bar();
let v = vec_of_strings!("a", "b", "c");
println!("{:?}", v);
assert_equal!(2 + 2, 4);
let map = hashmap!("a" => 1, "b" => 2);
println!("{:?}", map);
}
← Previous
Rust Traits Advanced — Associated Types, Default Generic Parameters, and Supertraits
Next →
Rust Unsafe Code — Unsafe Blocks, Raw Pointers, and FFI with C Code
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro