可以定义递归调用自身的宏:
macro_rules! impl_component {
// Empty case to end the recursion
($n:expr ;) => {};
// Match the current count, the current type, and whatever else comes after
($n:expr ; $t:ty $(, $rest:tt)*) => {
impl Component for $t {
fn index(&self) -> usize { $n }
}
// Recurse, incrementing counter and only passing the remaining params
impl_component!($n + 1; $($rest),*);
};
// For the first recursion, set the counter initial value to zero
($($types:tt),+) => { impl_component!(0; $($types),*); };
}
impl_component!(Foo, Bar, Baz);
生成的代码将包括如下实现:
impl Component for Baz {
fn index(&self) -> usize { 0 + 1 + 1 }
}
编译器会将这些表达式折叠成文本,因此结果与您所需的结果相等。