# 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:** 22

<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.

---

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