Can a struct be created with field keywords?

I can do this:

julia> struct Mystruct
       x
       y
       end

julia> function (m::Mystruct)(z)
       m.x+m.y+z
       end

julia> m=Mystruct(1,2)
Mystruct(1, 2)

julia> m(3)
6

but I would like to do this:

m = Mystruct(x=1,
             y=2)

as my real struct has enough fields that using keywords would be much more readable, but it doesn’t work (unsupported keyword arguments).

I can get the behavior I want by writing an outer constructor:

julia> Mystruct(;x,y) = Mystruct(x,y)
Mystruct

but that seems a bit unwieldy.

At this point in writing this post, I’ve discovered Parameters.jl, which seems to do what I want but mentions that the functionality may come into the language itself soon.

Thoughts on which path I should take?

The functionality is already in Base. You can try:

import Base.@kwdef

@kwdef struct Mystruct
    x = 1
    y = 2
end

It works like a normal struct and you can declare types as usual

@kwdef struct Mystruct{I <: Int64}
    x::I = 1
    y::I = 1
end
m = Mystruct()
Mystruct{Int64}(1, 1)

m = Mystruct(x=3)
Mystruct{Int64}(3, 1)
2 Likes

Thank you! Knowing what to search for I can see that in the release notes here https://pkg.julialang.org/docs/julia/THl1k/1.1.1/NEWS.html#Standard-library-changes-1.

1 Like