# 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:** 5\
**Page:** 2

<div class="post-metadata">

**Author:** ![pdeffebach](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pdeffebach/32/10320_2.png) [@pdeffebach](https://discourse.julialang.org/u/pdeffebach)\
**Post date:** [January 16, 2020, 1:30pm UTC](https://discourse.julialang.org/t/default-value-of-some-fields-in-a-mutable-struct/33408/21 "2020-01-16T13:30:04Z")

</div>

> [@Ferran\_Mazzanti](#):
>
> Now regarding the new solutions… again, they are not solutions as long as you have to give default values to all the fields, either in the constructor and when constructing an instance of that type. Please notice that I can leave undefined fields if I do not care about default values, like in

What behavior do you want the non-initialized fields to have? Presumably to throw an error for any operation using them? Or do you want the non-initialized values to propagate and return other non-initialized values after operations?

This is the difference between `nothing` and `missing` in Julia. Since Julia aims to have both more “programming” and more “data science” uses, we don’t want to require a single default behavior for non-initialized values.

The `Union{Nothing, Int64}` or `Union{Missing, Int64}` is the correct solution to your problem, and it has the benefit of being explicit about the behavior of your uninitialized values.

---

<div class="post-metadata">

**Author:** ![Jakub\_Wronowski](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jakub_wronowski/32/204030_2.png) [@Jakub\_Wronowski](https://discourse.julialang.org/u/Jakub_Wronowski)\
**Post date:** [January 16, 2020, 2:14pm UTC](https://discourse.julialang.org/t/default-value-of-some-fields-in-a-mutable-struct/33408/22 "2020-01-16T14:14:26Z")

</div>

@davidbp, great improvement!

I wrote a stub of the macro I mentioned:

```julia
macro awesome(s)
    if s.head !== :struct 
        error("Not a struct def")
    end 

    ismutable = s.args[1]
    if !ismutable
        error("Not mutable")
    end
    
    name = s.args[2]
    body = s.args[3]    

    ctor = :(function $(name)(;kwargs...)
                K = new()
                for (key, value) in kwargs
                    field_type_key = typeof(getfield(K,key))
                    setfield!(K, key, convert(field_type_key, value))
                end
                return K
            end)
            
    newbody = [body.args; ctor]
    
    return Expr(s.head, ismutable, name, Expr(body.head, newbody...))       
end

```

Now we can write:

```julia
@awesome mutable struct coly8
    x :: Int32
    y :: Float64
    z :: Bool
    t :: Int32
    u :: Float32
    v :: Bool
end

```

```julia
julia> coly8(u=4.0)
coly8(8, 9.200841125e-315, true, 0, 4.0f0, true)

```

The next step would be parsing a expression in a struct with predefined constants or use the `x::Int = 42` syntax like in Parameters.jl. Truly limitless set of options 🙂 I would add also zeroing of not defined fields like most of languages do.

---

<div class="post-metadata">

**Author:** ![Ahmed\_Salih](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ahmed_salih/32/206579_2.png) [@Ahmed\_Salih](https://discourse.julialang.org/u/Ahmed_Salih)\
**Post date:** [August 31, 2020, 11:06am UTC](https://discourse.julialang.org/t/default-value-of-some-fields-in-a-mutable-struct/33408/23 "2020-08-31T11:06:35Z")

</div>

Sorry for reopening this thread, would you happen to know if one can get this to work for arrays? An example is taking your macro and struct and redefining v as such:

```julia
v :: Array{Float32,1}

```

Then afterwards if you try to use `coly8(v=[2.f0;2.f0])`, then the error becomes:

```julia
ERROR: UndefRefError: access to undefined reference
Stacktrace:
 [1] coly8(; kwargs::Base.Iterators.Pairs{Symbol,Array{Float32,1},Tuple{Symbol},NamedTuple{(:v,),Tuple{Array{Float32,1}}}}) at ..
 [2] top-level scope at none:1

```

Or maybe there is another way to do this in Julia today?

EDIT: Figured it out using Parameters.jl

Kind regards

---

<div class="post-metadata">

**Author:** ![Fourier](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fourier/32/38176_2.png) [@Fourier](https://discourse.julialang.org/u/Fourier)\
**Post date:** [October 1, 2022, 8:08pm UTC](https://discourse.julialang.org/t/default-value-of-some-fields-in-a-mutable-struct/33408/24 "2022-10-01T20:08:54Z")

</div>

You may also take a look at `Base.@kwdef`.  
Here is an example:

```julia
  julia> Base.@kwdef struct Foo
             a::Int = 1 # specified default
             b::String # required keyword
         end
  Foo

  julia> Foo(b="hi")
  Foo(1, "hi")

  julia> Foo()
  ERROR: UndefKeywordError: keyword argument b not assigned

```

---

<div class="post-metadata">

**Author:** ![Jian\_ZUO](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jian_zuo/32/33738_2.png) [@Jian\_ZUO](https://discourse.julialang.org/u/Jian_ZUO)\
**Post date:** [October 2, 2022, 1:35pm UTC](https://discourse.julialang.org/t/default-value-of-some-fields-in-a-mutable-struct/33408/25 "2022-10-02T13:35:54Z")

</div>

Now the Base.@kwdef is exported and available in public API?

[Previous page](https://discourse.julialang.org/t/default-value-of-some-fields-in-a-mutable-struct/33408.md?page=1)
