# Julia learning macros / metaprogramming

**URL:** <https://discourse.julialang.org/t/julia-learning-macros-metaprogramming/45753>\
**Category:** New to Julia\
**Tags:** macros, metaprogramming, tutorials\
**Created:** [August 29, 2020, 4:33pm UTC](https://discourse.julialang.org/t/julia-learning-macros-metaprogramming/45753 "2020-08-29T16:33:34Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![WschW](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/wschw/32/6575_2.png) [@WschW](https://discourse.julialang.org/u/WschW)\
**Post date:** [August 29, 2020, 5:05pm UTC](https://discourse.julialang.org/t/julia-learning-macros-metaprogramming/45753/3 "2020-08-29T17:05:34Z")

</div>

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`

```julia
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

```julia
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

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

```

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

```julia
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.

```julia
struct MyType
  x::Int64
end

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

```

---

_[View the full topic](https://discourse.julialang.org/t/julia-learning-macros-metaprogramming/45753)._
