Separate macro for inserting fields in struct in the standard lib

Is there a def macro analogue in julia?

# Macro for inserting fields 
macro def(name, definition) 
  return quote
      macro $(esc(name))()
          esc($(Expr(:quote, definition)))
      end
  end
end

@def my_fields begin
     weights
     input_dim
     output_dim
end

mutable struct MyStruct
    @my_fields
end

You could use CompositeStructs.jl:

using CompositeStructs

struct MyFields
    weights
    input_dim
    output_dim
end

@composite mutable struct MyStruct
    MyFields...
end

In this case MyFields is also a struct, if you want to make sure no one can make an instance of MyFields and it serves only as a list of fields, you could also add an inner constructor MyFields() = error().

2 Likes