Macro for generating struct

I have written a macro that generates a new struct. It all works as intended when I test the macro from the REPL or from a script. Then of course, I want to call the macro in a function that does some cooking and returns a DataType defined by the macro. Kablooie, because of course, you can not define a struct inside a function.

So I reckon that I want the macro to generate some code, and evaluate it in the module to which the function calling the macro belongs.

Any thoughts on pulling this stunt? :grinning:

I am lazy and tryiiing to get away without a MWE. I really do look for trouble sometimes…

It sounds like you actually want to use eval() or @eval, in which case you don’t need a macro at all.

julia> function make_type_named(name)
         @eval struct $name end
make_type_named (generic function with 1 method)

julia> make_type_named(:hello)

julia> x = hello()

aha!!! eval evaluates into the macro! :+1: As simple as that…

Thank you!

You may be tempted to combine eval and macros in some way (perhaps by evaling a macro call or using eval inside a macro). Resist this temptation–it’s basically never necessary, since once you are using eval you no longer need a macro at all.


I agree. I burnt myself on this before. One things that crops up is “who’s interpolating”.

Thanks Robin!