0

I want to take a part of a field name in a macro, and then use it concatenated with the other part.

Here is an example in C:

#define MY_MACRO(NAME) cout << mystruct->foo_##NAME << endl;

I tried this:

macro_rules! MY_MACRO {
    ($NAME:ident) => {
        println!("{}", mystruct.concat_idents!(foo_, $NAME);
    }
}

But I get this:

error: expected one of `(`, `,`, `.`, `::`, `?`, or an operator, found `!`
  --> macrotest.rs:12:46
   |
12 |         println!("{}", mystruct.concat_idents!(foo_, $NAME));
   |                                              ^ expected one of `(`, `,`, `.`, `::`, `?`, or an operator
...
16 |     MY_MACRO!(bar);
   |     --------------- in this macro invocation
   |
Unai
  • 42
  • 5
  • 1
    Does this answer your question? [Is it possible to declare variables procedurally using Rust macros?](https://stackoverflow.com/questions/23061702/is-it-possible-to-declare-variables-procedurally-using-rust-macros) – tadman May 24 '21 at 00:17
  • @tadman well yes but actually no – Unai May 24 '21 at 00:55
  • Could you explain just a *little bit* more than that? – tadman May 24 '21 at 00:57
  • @tadman I edited the question, now is more specific... – Unai May 24 '21 at 01:00
  • 1
    `concat_idents!` is a macro and must be used on its own. It can't be used as if it's a function call. Try: `concat_idents!(mystruct.foo_, $NAME)` Try not to think of this in C terms with a pre-processor that expands. Rust's macros are a lot more elegant than that. – tadman May 24 '21 at 01:04
  • @tadman that doesn't work – Unai May 24 '21 at 03:29
  • @Unai this may help https://stackoverflow.com/a/61511576/3343860 – Dawer May 24 '21 at 06:32
  • Are you just missing a closing parenthesis? There should be 2, but it looks like you only have one. (happens to the best of us...) – Coder-256 May 25 '21 at 02:28

0 Answers0