2

Say I'd like to write a macro that takes an identifier and defines a function with the ident as part of its name:

macro_rules! defun {
    ( $name:ident ) => {
        fn fun_$name() { // This doesn't work, need to find a way
                         // to convert "foo" into "fun_foo"
            // ...
        }
    }
}

defun!(foo);

Is this possible?

P.S. My actual use case is more like

macro_rules! tests {
    ( $( $name:ident ),* $(,)* ) => {
        $(
            #[test]
            fn test_case_$name() {
                // ...
            }
        )*
    }
}

tests!{
    fixture1,
    fixture2,
}

for a bunch of integration tests.

4ae1e1
  • 7,228
  • 8
  • 44
  • 77
  • Also [Can a Rust macro create new identifiers?](https://stackoverflow.com/questions/27415011/can-a-rust-macro-create-new-identifiers) – trent Sep 16 '18 at 04:55
  • Thanks for referencing prior art. I wasn't able to find them. I guess the answer is no. – 4ae1e1 Sep 16 '18 at 04:56
  • 1
    It looks like the answer is no, but you can always namespace them instead (by putting them in a `mod`ule). `test_cases::fixture1` instead of `test_case_fixture1` etc. – trent Sep 16 '18 at 04:57
  • Yeah, I suppose so. – 4ae1e1 Sep 16 '18 at 04:58

0 Answers0