This seems like a great use case for a macro. You might take inspiration from https://github.com/mauro3/Parameters.jl which does something similar:
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> 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> 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