Michael
Michael

Reputation: 5062

In Julia: initialize fields with nothing

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

Upvotes: 1

Views: 1083

Answers (1)

hckr
hckr

Reputation: 5583

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)

Upvotes: 3

Related Questions