Array assignment is alias and assignment semantics

This is an extract of previous answers that are probably helpful:

In simple terms (which are the ones I can understand): You are always just giving a new label to the same value stored in the position in memory for which x is also a label:*

x = 3
y = x # points to the same value as x, thus y = 3
x = 4 # this simply assigns the x label to a new value, thus not affecting y

That is exactly the same for arrays:

x = [1,2]
y = x
x = [3,4] # x label bound to a new value, y unaffected

The confusion arises with the mutation syntax:

x = [1,2]
y = x
x[1] = 3
y == [3,2] # y was mutated

that is because one must distinguish x[i]= from x= : the x[i] notation is a syntactic sugar to the setindex! function, which does something different (mutates in place) the value in a specific position in memory.

*footnote: It is normal to initially distinguish arrays from scalars in what concerns that behaviour, because for scalars you cannot really distinguish if the new label points to the same position in memory or not than the previous scalar, since the values are the same anyway. Actually, it will be the compiler which will decide if one thing or the other will happen, depending on the context of the code. For arrays the copy and assignment are effectively distinguishable from the user point of view, and two different notations exist for them.

2 Likes