# Composition and inheritance: the Julian way

**URL:** https://discourse.julialang.org/t/composition-and-inheritance-the-julian-way/11231
**Category:** General Usage
**Tags:** inheritance, structtypes
**Created:** [May 29, 2018, 1:06pm UTC](https://discourse.julialang.org/t/composition-and-inheritance-the-julian-way/11231 "2018-05-29T13:06:00Z")
**Posts on this page:** 1
**Showing post:** 5

<div class="post-metadata">

### Author: ![dfdx](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dfdx/32/120_2.png) [@dfdx](https://discourse.julialang.org/u/dfdx)
#### Post date: [May 29, 2018, 1:33pm UTC](https://discourse.julialang.org/t/composition-and-inheritance-the-julian-way/11231/5 "2018-05-29T13:33:35Z")

</div>

You can always make a macro to avoid boilerplate code, e.g.:

```julia
abstract type AbstractPerson end

mutable struct Person <: AbstractPerson
    name::String
    age::Int
end

macro inherit(name, base, fields)
    base_type = Core.eval(@ __MODULE__ , base)
    base_fieldnames = fieldnames(base_type)
    base_types = [t for t in base_type.types]
    base_fields = [:($f::$T) for (f, T) in zip(base_fieldnames, base_types)]
    res = :(mutable struct $name end)
    push!(res.args[end].args, base_fields...)
    push!(res.args[end].args, fields.args...)
    return res
end

@inherit Citizen Person begin
    nationality::String
end

```

But honestly, I know very few tasks where field inheritance is indeed the best approach.

---

_[View the full topic](https://discourse.julialang.org/t/composition-and-inheritance-the-julian-way/11231)._
