Repetitions
- Rust course
- Advanced
- Lesson 43/81
- 4 min
Learn repetition patterns with $(...),*.
Repetitions
The most powerful part of macros is repetition patterns: $( ... ),* means "zero or more, comma-separated", $( ... ),+ "one or more", $( ... )? "optional". In the body, the same pattern repeats for each match:
macro_rules! topla {
($($x:expr),*) => {
0 $(+ $x)*
};
}
topla!(1, 2, 3) // 0 + 1 + 2 + 3
topla!() // 0The separator is part of the pattern: $(..),* expects commas, $(..);* semicolons.
Multiple arms
A macro can have several arms; the first match is used. Complex patterns can be built with recursion:
macro_rules! en_buyuk {
($x:expr) => { $x };
($x:expr, $($kalan:expr),+) => {
{ let a = $x; let b = en_buyuk!($($kalan),+); if a > b { a } else { b } }
};
}
en_buyuk!(3, 9, 4) // 9Practice Variadic sum
Write the topla! macro above. Print the results of topla!(1, 2, 3) and topla!() separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
macro_rules! topla {
($($x:expr),*) => {
0 $(+ $x)*
};
}
fn main() {
println!("{} {}", topla!(1, 2, 3), topla!());
}Expected output
6 0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Does <code>topla!(1, 2, 3,)</code> (trailing comma) match this macro?
- It warns
- Panic
- No; $(,)? must be added Correct answer
- Yes
Explanation: To accept a trailing comma, the pattern is written as ($($x:expr),* $(,)?); vec! is defined this way.
2 Repetition pattern
macro_rules! topla {
($($x:expr),____) => {
0 $(+ $x)*
};
}
macro_rules! topla {
($($x:expr),*) => {
0 $(+ $x)*
};
}
Explanation: * accepts zero or more repetitions.
3 Pattern and meaning
| Term | Meaning |
|---|---|
$(..),* |
Zero or more |
$(..),+ |
At least one |
$(..)? |
Optional |
$(,)? |
Trailing comma |