Confused by different behavior of assignments of Arrays and Numbers

Hello, everyone,

This is rudimentary, but I’am confused about Julia’s different “=” behaviors for Numbers and Arrays.

To my understanding, when we assign a variable to an object, we set the variable referred to the memory location of the object. Then if we assign this variable to another variable, behavior changes between numbers and arrays. Like this:

julia> x = 10
10
julia> x1 = x
10
julia> x1 === x
true
julia> x1 = 5
5
julia> x
10
julia> x1 === x
false

Which means for numbers, x1 initially is exactly the same with x before we assign a new object to it.

But for Arrays, this is a different story, like this:

julia> y = [10]
1-element Array{Int64,1}:
 10
julia> y1 = y
1-element Array{Int64,1}:
 10
julia> y1 === y
true
julia> y1[1] = 3
3
julia> y
1-element Array{Int64,1}:
 3
julia> y1 === y
true

Which means y1 and y always point to the same memory location. But we can use copy() and deepcopy() to separate y1 and y.

I know this is rudimentary, but I’m really curious about why it is designed this way? Why don’t we align these two different behaviours? Can anyone explain to me the mechanism underground?

Thanks!

This is a common source of confusion for beginners (myself included). You can find related threads about it. One nice answer is this one:

4 Likes

thank you for the link, very clearly explained!

1 Like