Declare new structs in a custom derive macro?

Is is possible to use a custom derive macro to define new structures?

Something like:

#[derive(MyDerive)]
struct MyStruct {
    foo: i32,
    bar: f32
}

where the macro would then in turn end up generating something like:

pub struct {
    first : MyStruct,
    second : MyStruct,
    type_from_name : #name,
    modified : Modified_ #name,
}

where the type_from_name and modified are just guesses at the syntax.
The idea is that type_from_name will have the type of the struct the macro was invoked on, and modified would set the type to a modification of that type name (assuming that is declared elsewhere).

The concept is that I want to write a crate that will "take" a user-defined struct as an input and define a whole hierarchy of structures around it, with those parent structs ultimately being used for serialization/deserialization.

And I realize that this construction may not exist because it's not meant to, and the real answer is: "Whatever you're trying to do should be a method or a trait". I'm still thinking through how to do ...

Yes; custom derive macros can produce arbitrary items (impl blocks, struct definitions, etc) at the same level as the annotated struct. According to the reference:

The input TokenStream is the token stream of the item that has the derive attribute on it. The output TokenStream must be a set of items that are then appended to the module or block that the item from the input TokenStream is in.

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.