Default value of *some* fields in a mutable struct

@davidbp, great improvement!

I wrote a stub of the macro I mentioned:

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:

@awesome mutable struct coly8
    x :: Int32
    y :: Float64
    z :: Bool
    t :: Int32
    u :: Float32
    v :: Bool
end
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 :slight_smile: I would add also zeroing of not defined fields like most of languages do.

9 Likes