How to prefix/suffix identifiers within a macro? [

2020-01-27 07:35发布

When using a macro that defines a function, is it possible to add a prefix to the function?

macro_rules! my_test {
    ($id:ident, $arg:expr) => {
        #[test]
        fn $id() {
            my_test_impl(stringify!($id), $arg);
        }
    }
}

For example, fn my_test_$id() {

I'm defining tests using an identifier which may begin with numbers, and I would like to use a common prefix.

标签: macros rust
3条回答
手持菜刀,她持情操
2楼-- · 2020-01-27 08:18

[...] is it possible to add a prefix to the function?

No. Really, really no. Super totally not at all even in the slightest.

I would like to have use a common prefix.

Put them all in a mod instead.

查看更多
祖国的老花朵
3楼-- · 2020-01-27 08:30

As mentioned, you should use submodules for this, but remember that macros can create submodules, submodules can be nested allowing their names to overlap, submodules can provide impls, and the tests submodule is not magic.

I once submitted a pull request that avoids numerous "boiler plate names" by refactoring the code using these tricks, although the #[no_mangle] exports make it harder.

查看更多
迷人小祖宗
4楼-- · 2020-01-27 08:34

Currently this is not supported in stable.


However there is a feature in nightly called concat_idents:

concat_idents!(my_test_, $id)

See

Update: it seems there aren't near-term plans to add this into stable releases, see issue.

查看更多
登录 后发表回答