1
votes

I have a mutable struct with optional fields like this:

mutable struct MyStruct
    field1::Union{Int, Nothing}
    field2::Union{String, Nothing}
    field3::Union{Int, Nothing}
    field4::Union{String, Nothing}
    # ...
end

I can now write a default constructor which initializes the fields with nothing:

MyStruct() = MyStruct(nothing, nothing, nothing, nothing)

This is not so nice when my struct has many fields. Also, I have to count the fields to get the constructor call with all the 'nothings' correct in this case. Is there a better way to do that?

Depending on the field content, I want to call different functions later:

if mystruct.field1 == nothing
  do_this()
else
  do_that()
end
1
I'm interested in the use case, but I'd also like to point out that last example is better suited to using parametric functions, ie f(::Nothing) = ...#something ; f(_) = ... #other thingstillearningsomething

1 Answers

3
votes

You can use fieldcount function to achieve that. This function gives you the number of fields of that an instance of given type would have. Here is an example containing a mutable struct and an outer constructor.

julia> mutable struct Foo
           x
           y
           z
       end

julia> Foo() = Foo(ntuple(x->nothing, fieldcount(Foo))...); # you can also fill an array and use `...`

julia> Foo()
Foo(nothing, nothing, nothing)