Julia like most other high level languages (oppose C) think of variables as pointers to data. Thus y=x doesn’t mean “make y hold a copy of x”, but instead means “make y a synonym for x”. Thus changing y, naturally, changes x. If you want a copy, you should instead write y=copy(x).
In addition, you may also find the behavior shown below helpful to keep in mind as a reference. Array slicing (things like a[:] where a is an array) also copies the underlying vector.
########################
Example 1
########################
julia> a = [1, 2, 3]
3-element Array{Int64,1}:
1
2
3
#creates a copy of a so changing b won't change a
julia> b = a[:]
3-element Array{Int64,1}:
1
2
3
julia> b[1]
1
julia> b[1] = 4
4
julia> b
3-element Array{Int64,1}:
4
2
3
julia> a
3-element Array{Int64,1}:
1
2
3
########################
Example 2
########################
julia> a = [1, 2, 3]
3-element Array{Int64,1}:
1
2
3
#b is synonymous with a so changing b will change a
julia> b = a
3-element Array{Int64,1}:
1
2
3
julia> b[1]
1
julia> b[1] = 4
4
julia> b
3-element Array{Int64,1}:
4
2
3
julia> a
3-element Array{Int64,1}:
4
2
3
For more information, I would encourage reading “Gotcha #5: Views, Copy and Deepcopy” in
What is the advantage of using pointers to same data when we write b = a? When we create a new variable with the value of old, it is usually to modify the data in the new one. Even though I have seen this behavior in other languages also, I’m yet to understand why such a “confusing” behavior is so widespread in many languages?
The behavior is useful because copying data can be expensive. Saying b = a avoids a copy. Moreover, it’s sometimes useful to keep the same array in different forms without copying the underlying data. Again, the behavior of b = a let’s you achieve that.
"(Such behavior) is very useful because it also allows you to keep the same array in many different forms. For example, we can have both a matrix and the vector form of the matrix using:
a = rand(2,2) # Makes a random 2x2 matrix
b = vec(a) # Makes a view to the 2x2 matrix which is a 1-dimensional array
Now “b” is a vector, but changing “b” still changes “a”, where “b” is indexed by reading down the columns. Notice that this whole time, no arrays have been copied, and therefore these operations have been excessively cheap (meaning, there’s no reason to avoid them in performance sensitive code)."