Search code examples
rustrust-macros

Can a macro access the field names and types of a remote struct from its path?


I am trying to create a macro that can copy the fields of some external struct into the struct where the macro is applied. So something like:

// external_crate.rs
pub struct ExternalStruct {
    foo: String,
    bar: i32,
}

// my_code.rs
#[copy_fields(external_create::ExternalStruct)] // how do I create this macro?
pub struct LocalStruct;

// generated output
pub struct LocalStruct {
    foo: String,
    bar: i32,
}

I understand I can parse and access the fields on which the macro is applied (i.e LocalStruct if it had any fields) but not sure if its possible to do this given the path of some other struct.


Solution

  • No, it is not possible. You can wrap the declaration site of the other struct with the macro too and memoize it in a static, but it is not guaranteed to work (although it currently does). You won't have access to the full path, though, only to the name.