Convenient way to create a copy of an immutable struct with a changed field

It might sound a bit weird but I am facing the following issue quite often:

Given a largish struct:

struct Foo
    a
    b
    c
    d
    e
    f
    g
    h
    i
    j
end

And a bunch of them in a Vector

foos =  [Foo(rand(10)...) for _ ∈ 1:10]

I’d like to “alter” e.g. one field (e.g. subtracting 23 from each .h), by creating an exact copy with the new values of .h.

Something like

altered_foos = copy(foos, but = :h=>x->x-23)

Is there a somewhat convenient method/package or whatever to do this other than writing out the a new constructor? I’d like to avoid code repetition and also tried it via meta programming but I have the feeling this has been solved before.

Edit: no, I don’t want to make it mutable :wink:

1 Like

https://github.com/jw3126/Setfield.jl maybe.

5 Likes

That was fast :joy:

Awesome, it’s like lenses in haskell. Thanks!