Struct definition as String

Hello,
I'm relatively new to the Rust language.
I want to create a small project that helps me generate API from Rust. For example, I have a Rust struct that represents the type sent by API, and I want to produce a file with a ReasonML representation of the type.
Is it possible to read struct definition as a string?

It sounds like you are looking for the thing called a proc-macro.

3 Likes

You're in luck!

As Alice said, procedural macros are what you want. [relevant book chapter]. As an incredibly oversimplified summary, you put it on your struct definition like this:

#[my_proc_macro]
struct MyStruct {
    foo: Foo,
    bar: Bar,
}

And the abstract-syntax-tree for this is fed into your procedural macro. This is related to derive, and beyond the standard library you'll often encounter this in serde.

Typically these proc macros just output another AST which gets fed back into that location of the rust program to be compiled. In terms of how you would make it generate an output file, well, maybe you would make a derive macro that implements a trait along the lines of:

trait StaticallyGeneratesMySpecialOutputFile: Sized {
    fn generate_the_special_output_file() -> &'static str;
}

And then you could relatively easily make some binary with a main function which uses this trait on your desired types to write to the output files you want.

1 Like