ERROR: setfield! immutable struct cannot be changed in Julia

Viewed 1292

I am updating some old code and I am now getting errors: ERROR: setfield! immutable struct cannot be changed in Julia when I try to change the values of an immutable struct. Is there a common workaround for how I can edit/mutate those values (this may be a rather silly question given that the type is explicitly immutable so it's not a good idea generally to try and change it).

1 Answers

As far as I remember immutables can not be safely manipulated even if you get a memory pointer to them and try to use ccal.

However, as an imperfect workaround you can consider using Setfield package as in the example below.

using Setfield
struct S
    a::Int
    b::String
end

Using:

julia> s = S(2, "hello")
S(2, "hello")

julia> s = @set s.a = 5
S(5, "hello")

Note that in many scenarios this might be faster than actually changing type of S to mutable.

Related