I have this problem of trying to create a struct which is a new copy of an existing struct with specific fields changed. I know that it is probably possible to achieve through metaprogramming. However, would that be the correct approach here or would I reinvent the wheel?
E.g:
struct A
a
b
end
var = A(1,2)
var.b = 4 # This means var = A(1,4)
Update: Check Accessors.jl, the successor to:
Setfield.jl is a package to do exactly that.
I usually go with defining the struct
with Base.@kwdef
and then define an outer constructor like
Base.@kwdef struct A
a
b
end
Base.convert( ::Type{NamedTuple}, a::A ) = NamedTuple{propertynames(a)}(a)
function A( a::A; kwargs... )
nt = convert(NamedTuple, a)
nt = merge( nt, kwargs.data )
return A(;nt...)
end
and then you can do
var = A(1, 2)
var2 = A(var, b = 4)
you could also define setindex!
to get the syntax you had in the OP, but that would only let you change one field at a time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With