As @JeffreySarnoff says, I don’t know that it is the best approach for your particular situation to have “unassigned” values, however, I think what you are looking for is nothing
or missing
. You could (but maybe shouldn’t) define animal like so:
mutable struct animal{T}
x::Union{Nothing,Int}
y::Union{Nothing,T}
animal{T}() where{T} = new{T}(nothing,nothing)
end
Then these values would be set to the value nothing
until you assigned them. That said, it might make more sense to write different data structures for the different scenarios you describe, rather than using one large data structure with unassigned values. For example:
struct Kangaroo
x::Int
end
struct Wallaby{T}
y::T
end
You could then write specific methods that do something different depending on the type. For example
jump(k::Kangaroo) = Kangaroo(k.x+10)
jump(w::Wallaby) = Wallaby(w.y+1)
Without knowing more details about your exact situation, it is hard to know what to do for your specific use case.
You almost certainly want a Union{Missing, T}
field then, possibly with a keyword constructor with nothing
or missing
as the default (read the manual about the difference and pick the one that suits your semantics better).
Eg
Base.@kwdef mutable struct Crocodile # note: type name capitalized
teeth::Union{Int,Missing} = missing
legs::Union{Float64,Missing} = missing
end
then
julia> c = Crocodile(; teeth = 42)
Crocodile(42, missing)
julia> c.teeth
42
julia> c.legs
missing
It is unclear why you need an inner constructor (I may have missed something).
Thanks to you all for the comments, the proposed solution seems to work well
In any case and in reference to the different solutions including missing and undef terms, I just want to avoid them because the proposed structure I’m using is still under development, and somehow I feel quite free to add more fields as required to the main type. I’m of all the warnings provided so far and was considering to use them once the codes are in its final form, but right now it is easier to simply add fields as required and do nothing else… which, by the way, has been working great so far, no bugs or whatsoever.
Still I’ll consider these possibilities in the future versions, thanks.