当内部宏接受参数时,如何定义一个宏来定义另一个宏? [英] How do I define a macro which defines another macro when the inner macro takes arguments?

查看:201
本文介绍了当内部宏接受参数时,如何定义一个宏来定义另一个宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要复制的最小代码:

macro_rules! test {
    ($name:ident: $count:expr) => {
        macro_rules! $name {
            ($($v:expr),*) => {}
        }
    }
}

test!(yo: 123);

错误:

error: attempted to repeat an expression containing no syntax variables matched as repeating at this depth
 --> src/lib.rs:4:15
  |
4 |             ($($v:expr),*) => {}
  |               ^^^^^^^^^

删除$count:expr或将$count:expr更改为类似$count:block的另一种类型都忽略了该错误,但我确实需要将其设置为expr.错误是什么意思?

Removing $count:expr or changing $count:expr to another type like $count:block omits the error, but I really need it to be expr. What does the error mean?

推荐答案

这是已知问题(#35853).当前建议的解决方法是将美元符号$作为单独的令牌传递.然后您可以打电话给自己,并传入$:

This is a known issue (#35853). The current recommended workaround is to pass in the dollar sign $ as a separate token. You can then call yourself, passing in the $:

macro_rules! test {
    ($name:ident: $count:expr) => { test!($name: $count, $) };

    ($name:ident: $count:expr, $dol:tt) => {
        macro_rules! $name {
            ($dol($v:expr),*) => {}
        }
    };
}

fn main() {
    test!(yo: 2);
    yo!(42);
}

这篇关于当内部宏接受参数时,如何定义一个宏来定义另一个宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆