Create struct and implementation with proc_macro

I want to create a struct and it's implementation with a proc_macro.
The argument for the proc_macro is an existing struct.
The syntax is:

struct RefStruct {
    a: u32,
    b: Vec<u8>


The result should be a new struct with some different contents.
My current implementation of the macro starts with:

pub fn create_getters(input: TokenStream) -> TokenStream {
    let DeriveInput { ident, data, .. } = parse_macro_input!(input);

The problem is that it fails in the first line because it expects a struct, enum or union, because just the struct name is provided.

How can I get the struct contents when the struct name is provided?

You don't.

Macros get the exact, literal tokens you provide when you invoke them, and that's it. If you need the definition of the struct for the macro to work, then you have to pass the definition of the struct to the macro explicitly.

You might want to look at changing to a proc macro attribute, and invoking it like this:

struct RefStruct {
    a: u32,
    b: Vec<u8>,

The thing a proc macro attribute is attached to is considered part of its input. If you're implementing a specific trait, then you probably want a proc macro derive.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.