# Can the fields of a Julia type have default values?

**URL:** <https://discourse.julialang.org/t/can-the-fields-of-a-julia-type-have-default-values/113601>\
**Category:** General Usage\
**Tags:** question, type\
**Created:** [April 29, 2024, 5:51am UTC](https://discourse.julialang.org/t/can-the-fields-of-a-julia-type-have-default-values/113601 "2024-04-29T05:51:31Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![WuSiren](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/wusiren/32/42529_2.png) [@WuSiren](https://discourse.julialang.org/u/WuSiren)\
**Post date:** [April 29, 2024, 5:51am UTC](https://discourse.julialang.org/t/can-the-fields-of-a-julia-type-have-default-values/113601/1 "2024-04-29T05:51:31Z")

</div>

```julia
julia> struct MyType n::Int64 end

julia> a = MyType(3)
MyType(3)

julia> a.n
3

julia> b = MyType()
ERROR: MethodError: no method matching MyType()

```

Can I set a default number for the field `n` (e.g., `n = 1` by default) so that I can call the type without any input argument?

---

<div class="post-metadata">

**Author:** ![screw\_dog](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/screw_dog/32/48119_2.png) [@screw\_dog](https://discourse.julialang.org/u/screw_dog)\
**Post date:** [April 29, 2024, 5:54am UTC](https://discourse.julialang.org/t/can-the-fields-of-a-julia-type-have-default-values/113601/2 "2024-04-29T05:54:02Z")

</div>

`@kwdef` is what you want. This lets you do:

```julia
@kwdef struct MyType
  n::Int64 = 3
end

b = MyType()
b.n == 3

```

---

<div class="post-metadata">

**Author:** ![WuSiren](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/wusiren/32/42529_2.png) [@WuSiren](https://discourse.julialang.org/u/WuSiren)\
**Post date:** [April 29, 2024, 5:57am UTC](https://discourse.julialang.org/t/can-the-fields-of-a-julia-type-have-default-values/113601/3 "2024-04-29T05:57:40Z")

</div>

Nice. Thanks! 🤝

---

<div class="post-metadata">

**Author:** ![torrance](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/torrance/32/38990_2.png) [@torrance](https://discourse.julialang.org/u/torrance)\
**Post date:** [April 29, 2024, 6:30am UTC](https://discourse.julialang.org/t/can-the-fields-of-a-julia-type-have-default-values/113601/4 "2024-04-29T06:30:45Z")

</div>

For reference, here it is in the docs: [Essentials · The Julia Language](https://docs.julialang.org/en/v1/base/base/#Base.@kwdef)

---

<div class="post-metadata">

**Author:** ![WuSiren](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/wusiren/32/42529_2.png) [@WuSiren](https://discourse.julialang.org/u/WuSiren)\
**Post date:** [April 29, 2024, 6:35am UTC](https://discourse.julialang.org/t/can-the-fields-of-a-julia-type-have-default-values/113601/5 "2024-04-29T06:35:51Z")

</div>

Thanks!
