Search code examples
rustrust-macros

Is it possible to change/generate code through derive macro inside of the struct that uses that macro?


I was curious whether it is possible to change the code inside the struct that uses derive macro, or are you only limited to generating the new code outside?

Example

Adding another field to the Building struct through SomeMacro.


#[derive(SomeMacro)]
pub struct Building {
  colour: String, 
  // Add height: u8 through derive macro
}

Solution

  • It is not possible. This is a fundamental characteristic of derive macros: they take an existing item's tokens and generate new, separate items (usually trait impls).

    If you want to modify the struct item itself, you must instead make an attribute macro, which can return a replacement for the input tokens. Attribute macros aren't invoked using the derive attribute but are attributes themselves: #[some_macro] pub struct Building { ...