Struct with new instances according to arguments passed

Hello,

I would like to know if there exists any concise solution to create a struct which can be initialised with any number of arguments? like so:

struct VariableStruct
a
b
c
d
e
f
return new(;a,b,c,d,e,f)
end
  1. With one argument

So now if I would like to initiate a new instance of VariableStruct with only say e declared like so:

myVar= VariableStruct(e=5)

then I’d like myVar to be initialised as VariableStruct(nothing, nothing,nothing, nothing,5,nothing)

  1. With say 3 arguments

Initiate a new instance of VariableStruct with only say a,d,e declared like so:

myVar = VariableStruct(a=1,d=3,e=5)

then I’d like myVar to be initialised as VariableStruct(1, nothing,nothing, 3 ,5 ,nothing)

Does this functionality exist? Or in other words how to achieve it?
As you may noticed I used Kwargs, this is an idea I have preemptively tried to put in my question :slight_smile:

Parameters.jl

2 Likes

Just create a constructor that takes kwargs initialized to nothing?

1 Like

This is possible without adding new packages. As @gustaphe said, you can define a new inner constructor with default values:

julia> struct VariableStruct
       a
       b
       c
       d
       e
       f
       VariableStruct(;a = nothing,b = nothing,c = nothing,d = nothing,e = nothing,f= nothing) =  new(a, b, c, d, e, f)
       end


julia> VariableStruct()
VariableStruct(nothing, nothing, nothing, nothing, nothing, nothing)

julia> VariableStruct(a = 1)
VariableStruct(1, nothing, nothing, nothing, nothing, nothing)

julia> VariableStruct(a = 1, f = 2)
VariableStruct(1, nothing, nothing, nothing, nothing, 2)
2 Likes

Thanks for the explanation))

You can also use Base.@kwdef which basically expands to @aramirezreyes’s answer:

using Base: @kwdef

@kwdef struct VariableStruct
    a = nothing
    b = nothing
    c = nothing
    d = nothing
    e = nothing
    f = nothing
end

VariableStruct(a=1) # ...
1 Like