Problem with mutation and copying of Matrices/Vectors

@stevengj
Thank you very much for your explanations which are very helpful.
It seems that I am confused between the terms “Replace”, “overwrite”, “change”. I am also confused between:

R.I .= @SVector [3,4,5] # .= changes the *contents* of R.I
R.I = @SVector [3,4,5] # = does not work as (changing the *contents* of R.I also?)

It seems that I am confused between the two terms “Replace”, and “change”. Could you please explain the difference to me?

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