advancedMacros
Macros with Repetition
Use repetition patterns in macros with $().
Macros with Repetition
Use repetition patterns in macros with $().
Difficulty
Advanced
Code
rust
macro_rules! make_vec {
($($x:expr),* $(,)?) => {
vec![$($x),*]
};
}
macro_rules! print_all {
($($x:expr),*) => {
$(
println!("{}", $x);
)*
};
}
macro_rules! sum {
($($x:expr),*) => {
{
let mut total = 0;
$(
total += $x;
)*
total
}
};
}
fn main() {
let v = make_vec![1, 2, 3, 4, 5];
println!("{:?}", v);
print_all!["hello", "world", "rust"];
let s = sum![1, 2, 3, 4, 5];
println!("sum: {}", s);
}Explanation
Macro repetition: $($x:expr),* matches comma-separated items.
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.