I’m curious if there’s a proper Julian way to implement optional struct fields through an effective Union{T, Nothing}.
I’ve written the macro below and it seems to work for my very simple test case. Is there a better way to achieve this? I suppose there could also be a macro for specific fields instead of the whole struct.
macro optional(block::Expr)
struct_name = block.args[2]
fields_expr = block.args[3].args
fields = Expr[]
for field ∈ fields_expr
if typeof(field) !== LineNumberNode
s = field.args[1]
t = field.args[2]
new_field = :($(s)::Union{$(t), Nothing})
push!(fields, new_field)
end
end
esc(quote
struct $struct_name
$(fields...)
end
end)
end
@optional struct A
x::Float64
y::Float64
end
a = A(1.0, nothing)
println(a)