Macro that generate struct

How to generate a struct with macro? let's say we have a JSON which is like:

    "fields": [{
          "name": "a",
          "type": "String"

and generate a struct like:

struct Foo {
    a: String

Ignoring the fact that the struct name isn't specified anywhere, you would need a proc macro due to the fact that the field name and type are strings.

Would you mind being more explicit? and how to pass the content of a vec to the macro since fields is actually JSON array

Right now "Foo" isn't specified anywhere in the JSON, so you have to figure out how you're coming up with the struct name.

You will have to use a procedural macro, which takes the raw tokens from the compiler. It's not going to be trivial to do. If all you want is a JSON-like syntax and not actual JSON, you should not add quotes around the field name and type, which will let you use macro_rules!.

You can probably use a build script here.
A build script is a rust program that runs before the rest of the code is compiled.
It would read the json file and write the strut to be generated into a file that is then included in the remaining Rust code.

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.