The following code allows to modify a field of an immutable compsite type, and I am not sure why is this allowed:
struct A
a :: Vector{Int}
function A(a :: Vector{Int})
new(a)
end
end
myA = A([1,2,3])
@show myA.a # myA.a = [1, 2, 3]
push!(myA.a, 4)
@show myA.a # myA.a = [1, 2, 3, 4]
Instead, modifying it through a type method is not allowed:
struct A
a :: Vector{Int}
function A(a :: Vector{Int})
new(a)
end
end
function changeAa!(myA::A, a::Vector{Int})
myA.a = a
end
myA = A([1,2,3])
changeAa!(myA, [1,2,3,4])
Which yields: ERROR: LoadError: setfield!: immutable struct of type A cannot be changed
(as it should).
Looking at this question, it seems that the object that the field is pointing to needs to be preserved (which is the case for push!
), but I am still unsure how I could implement that myself. Can someone please elaborate on this? Thanks.