Julia learning macros / metaprogramming

Heres a short overview.
Note: I wrote this on my phone and haven’t been able to test it so there may be some bugs in the sample code.

quote or :( )
Use it for constructing blocks of code.
edit: added missing esc

macro shared_fields()
  esc(quote
    field1::Int
    field2::Float64
  end)
end

struct astruct
  @shared_fields()
  field3::Uint
end

struct bstruct
  @shared_fields()
  field3::String
end

$
Splices in code

macro double_input(fn, x)
  quote
    # If x is an expression with side effects like `print(b)`
    # we don't want to do that twice so we assign it to `z` first.
    z = $(x)
    $(fn)(z, z)
  end
end

@double_input div 3
# returns 1

esc
Use it for variables assigned to in macros that you want visible externally

macro setvar(x, y)
  quote
    $(esc(x)) = $(y)
  end
end

Meta.quot
Allows you to splice in code without interpolating it.

macro print_code(x)
  :(println($(Meta.quot(x))))
end

eval
Shouldn’t be used in macros or functions for the most part. It can be however useful to use at top level if you have a large number of similar functions to define.

struct MyType
  x::Int64
end

for op in [:(+), :(-), :(*), :(/)]
  @eval Base.$(op)(x::MyType, y::MyType) = MyType($(op)(x.x, y.x))
end
10 Likes