# Adding methods with metaprogramming

**URL:** <https://discourse.julialang.org/t/adding-methods-with-metaprogramming/42518>\
**Category:** General Usage\
**Tags:** metaprogramming\
**Created:** [July 4, 2020, 10:24am UTC](https://discourse.julialang.org/t/adding-methods-with-metaprogramming/42518 "2020-07-04T10:24:21Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sw72](https://avatars.discourse-cdn.com/v4/letter/s/b77776/32.png) [@sw72](https://discourse.julialang.org/u/sw72)\
**Post date:** [July 4, 2020, 10:24am UTC](https://discourse.julialang.org/t/adding-methods-with-metaprogramming/42518/1 "2020-07-04T10:24:21Z")

</div>

I have a couple of types defined like this:

```julia
struct Foo
    foo
end

struct Bar
    foo::Foo
    bar
    baz
end

```

Then I have a bunch of functions defined for `Foo`, with additional methods for `Bar` that just pass through the `foo` field:

```julia
func1(f::Foo, x) = x + f.foo
func1(b::Bar, x) = func1(b.foo, x)

func2(f::Foo, x, y) = x*y - f.foo
func2(b::Bar, x, y) = func2(b.foo, x, y)

```

Is there some way to generate the `Bar` methods automatically, using a macro or something?

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [July 4, 2020, 11:58am UTC](https://discourse.julialang.org/t/adding-methods-with-metaprogramming/42518/2 "2020-07-04T11:58:12Z")

</div>

Yes, see the [metaprogramming docs](https://docs.julialang.org/en/v1/manual/metaprogramming/) around the example

```julia
for op = (:sin, :cos, :tan, :log, :exp)
    @eval Base.$op(a::MyNumber) = MyNumber($op(a.x))
end

```

This is a very common pattern, you can find many similar ones in the Julia source code and packages.
