# Default value of \*some\* fields in a mutable struct

**URL:** <https://discourse.julialang.org/t/default-value-of-some-fields-in-a-mutable-struct/33408>\
**Category:** General Usage\
**Tags:** struct\
**Created:** [January 15, 2020, 5:31pm UTC](https://discourse.julialang.org/t/default-value-of-some-fields-in-a-mutable-struct/33408 "2020-01-15T17:31:51Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [January 15, 2020, 8:19pm UTC](https://discourse.julialang.org/t/default-value-of-some-fields-in-a-mutable-struct/33408/4 "2020-01-15T20:19:50Z")

</div>

This seems like a _great_ use case for a macro. You might take inspiration from [https://github.com/mauro3/Parameters.jl](https://github.com/mauro3/Parameters.jl) which does something similar:

```julia
julia> using Parameters

julia> @with_kw struct Foo
         x::Int32 = 1
         y::Float64
       end
Foo

julia> Foo(y = 2)
Foo
  x: Int32 1                                                                                                                                                                                                                                                                                                                          
  y: Float64 2.0 

```

Note that `@with_kw` doesn’t give the behavior you’re looking for. Instead, it throws an error if any field without a default is not provided:

```julia
julia> Foo()
ERROR: Field 'y' has no default, supply it with keyword.

```

But that’s an intentional design decision, and you could write something similar to `@with_kw` that would do exactly what you want. There is also related work in `@kwdef` which is supplied with Julia base:

```julia
julia> Base.@kwdef struct Bar
         x::Int32 = 1
         y::Float64
       end
Bar

julia> Bar(y = 2)
Bar(1, 2.0)

julia> Bar()
ERROR: UndefKeywordError: keyword argument y not assigned

```

---

_[View the full topic](https://discourse.julialang.org/t/default-value-of-some-fields-in-a-mutable-struct/33408)._
