1

I made a simple macro that defines a struct.

macro_rules! __body {
  ($($body:tt)+) => {
    $($body)+
  };
}

macro_rules! new_struct {
  ($(#[$attr:meta])* struct $name:ident { $($body:tt)+ } ) => {
    $(#[$attr])* struct $name {
      __body!($($body)+);
    }
  };
}

new_struct! {
  #[derive(Deserialize)]
  struct Test {
    a: bool,
    b: String,
  }
}

When I compile this code, it raises an error:

   |
14 |         __body!($($body)+);
   |               ^ expected `:`
...
19 | / new_struct! {
20 | |   #[derive(Deserialize)]
21 | |   struct Test {
22 | |     a: bool,
23 | |     b: String,
24 | |   }
25 | | }
   | |_- in this macro invocation
   |
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
jxlczjp77
  • 11
  • 1
  • If you just use the `$body` tokens directly, rather than pass them to another macro, this will work fine. ie `$($body)+` instead of `__body!($($body)+);`. – Peter Hall Jun 22 '20 at 08:31

1 Answers1

2

According to the reference:

Macros can expand to expressions, statements, items (including traits, impls, and foreign items), types, or patterns.

and struct fields are none of these, so you cannot use a declarative macro for that. You may want to try procedural macros instead.

mcarton
  • 27,633
  • 5
  • 85
  • 95
Kitsu
  • 3,166
  • 14
  • 28