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
}
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 impl
s).
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 { ...