Macro Rules
Macro Repetition
Capture a List
A macro repetition can accept a comma-separated list and expand that list into another expression.
Program
Play the program to choose the middle word in a repeated macro input.
macro_repetition_words.rs
macro_rules! collect_words {
($($word:expr),+ $(,)?) => {{
let values = vec![$($word),+];
values.join(",")
}};
}
fn main() {
let extra = ;
let joined = collect_words!("red", extra, "blue");
println!("{joined}");
}
macro_rules! collect_words {
($($word:expr),+ $(,)?) => {{
let values = vec![$($word),+];
values.join(",")
}};
}
fn main() {
let extra = ;
let joined = collect_words!("red", extra, "blue");
println!("{joined}");
}
macro_rules! collect_words {
($($word:expr),+ $(,)?) => {{
let values = vec![$($word),+];
values.join(",")
}};
}
fn main() {
let extra = ;
let joined = collect_words!("red", extra, "blue");
println!("{joined}");
}
repetition
`$($word:expr),+` captures one or more comma-separated expressions.
optional trailing comma
`$(,)?` accepts a final comma without requiring one.
expansion list
`$($word),+` repeats the captured expressions inside `vec!`.