Problem with mutation and copying of Matrices/Vectors

julia> struct IntVectorWrapper; v :: Vector{Int}; end

julia> x = IntVectorWrapper(Int[1, 2, 3]);

julia> x.v = [4, 5, 6]
ERROR: setfield! immutable struct of type IntVectorWrapper cannot be changed
Stacktrace:
 [1] setproperty!(::IntVectorWrapper, ::Symbol, ::Array{Int64,1}) at ./Base.jl:34
 [2] top-level scope at REPL[3]:1

julia> empty!(x.v); append!(x.v, [4, 5, 6]); x.v
3-element Array{Int64,1}:
 4
 5
 6

It is not about the terms, it is about what you are changing/replacing/mutating. You cannot change/replace/mutate x directly because it is immutable. However, the vector object stored in x.v is a mutable object (because vectors are mutable), so you can change it. You just cannot ever change x, so x will always point to the same mutable object in x.v and you must change the stored object itself, and not which object is stored there. Is it clearer?

1 Like