Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prefix/suffix identifiers within a macro? [duplicate]

Tags:

macros

rust

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.

like image 531
ideasman42 Avatar asked Aug 18 '16 12:08

ideasman42


3 Answers

[...] 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.

like image 28
DK. Avatar answered Nov 05 '22 16:11

DK.


Currently this is not supported in stable.


However there is a feature in nightly called concat_idents:

concat_idents!(my_test_, $id)

See

  • Rust docs
  • Issue

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

like image 165
ideasman42 Avatar answered Nov 05 '22 15:11

ideasman42


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.

like image 3
Jeff Burdges Avatar answered Nov 05 '22 16:11

Jeff Burdges