Macro define with struct attribute

Is there anyone can tell me how to define a macro with Struct attribute?

main.rs

struct Pupil {
name: String,
info: String
}

...

#[defined_model(Pupil)]
fn modify(name: String, info: String) {
}

lib.rs

#[proc_macro_attribute]
pub fn defined_mode(attr: TokenStream, input: TokenStream) -> TokenStream {
???
}

Macros run before the compiler knows which types exist, so you can't look up the definition of structs unless the macro is annotated on the struct definition itself.

1 Like

Then in order to use the struct inside of the macro, do i have to derive it? using #derive macro

What is your macro supposed to do? The answer depends on what you need.

I need to use struct inside of macro.
let's assume that I create a module and all the constructor and member functions of it should be user-defined outside of the macro.

That's impossible. Macros have access only to the information they are provided.

You can parse the Pupil from the input and then expand to code like Pupil::new(), Pupil::do_something() or whatever if that's what you need.

1 Like

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.