我的目标是制作一个能够以一种我可以描述元组初始化的方式展开的宏.
我做了这个玩具的例子:
macro_rules! fill_tuple {
($_idx : expr) => {};
($idx : expr, $kind : ident) => {
$idx
};
($idx : expr, $head : ident, $($tail : ident),+) => {
fill_tuple!($idx, $head),
fill_tuple!($idx + 1usize, $($tail),+)
};
}
fn main()
{
(
fill_tuple!(0usize, A,B,C)
)
}
这里的 idea 是,有3个参数,所以展开后应该得到(0,1,2).这只是一个例子,在最后,我将以一种更复杂的方式使用A、B、C来初始化元组.
我目前的障碍是宏最后一块上的逗号不被Ruust接受.我得到的错误是:
Compiling playground v0.0.1 (/playground)
error: macro expansion ignores token `,` and any following
--> src/main.rs:7:33
|
7 | fill_tuple!($idx, $head),
| ^
...
15 | fill_tuple!(0usize, A,B,C)
| --------------------------- help: you might be missing a semicolon here: `;`
| |
| caused by the macro expansion here
|
= note: the usage of `fill_tuple!` is likely invalid in expression context
我怎么才能绕过这个问题呢?我绝对需要那个逗号,否则整个生成的代码都是错误的.