Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a new structure with fields changed in Julia

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)
like image 254
JKRT Avatar asked Jan 01 '23 13:01

JKRT


2 Answers

Update: Check Accessors.jl, the successor to:

Setfield.jl is a package to do exactly that.

like image 191
Jakob Nissen Avatar answered Jan 25 '23 22:01

Jakob Nissen


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.

like image 29
loki Avatar answered Jan 25 '23 22:01

loki