Why?
I started this post because I found that array assignment created an alias, leading to an unexpected problem. I wasn’t sure if this was a bug.
But it’s now clear that it is the expected behavior. So my goals are
- to help others who may encounter this;
- to understand how assignment semantics work in general, and how to find out information on same;
- to take some probably ineffective shots at the documenation .
Behavior
Apparently if aa
is an Array
and I set bb = aa
then changing the elements of bb
changes the elements of aa
. See the example at the bottom if you don’t believe it! Perhaps overly influenced by R, which semantically treats the two as independent (while avoiding unnecessary copies behind the scenes), I found this surprising.
For the record, if this behavior is a problem for you, a solution is to use bb = copy(aa)
.
Help/Learning
How do I know what I’m getting when I do y = x
? My current concern is with x
having the Array
type, but I’d also like to know how to find out for other types. I can think of at least 3 possibilities:
y
could be a completely separate copy ofx
;- it could be some kind of view of
x
; or - it could be an alias for
x
.
The question probably presupposes that =
could behave differently for different types on the rhs (and what if the lhs already has a type?), and I’m not at all sure that’s true. (I am perhaps overly influenced by my experience with C++ which can do all kinds of sneaky stuff relating to assignment.)
Documentation
When I looked in the documentation I couldn’t find anything in the discussion of Array
s addressing this issue—only the semantics of assignments with indexing.
While writing this note I finally did find some stuff in the documenation.
Array assignment behavior is mentioned in the second item on Noteworthy Differences from other Languages · The Julia Language, which is for MATLAB (which I ignored since I don’t use it). It doesn’t seem to be in the discussion of differences from R.
Essentials · The Julia Language has an entry for the “keyword” =. It says
For variable
a
and expressionb
,a = b
makesa
refer to the value ofb
.
which IMO doesn’t help that much. But the examples section does go on to make it crystal clear for arrays:
Assigning
a
tob
does not create a copy ofb
; instead usecopy
ordeepcopy
.
which seems like a point that should have appeared earlier. This is followed by an example in the same spirit as my own session, appearing next.
Example
julia> aa = [1, 2, 4]
3-element Vector{Int64}:
1
2
4
julia> bb = aa
3-element Vector{Int64}:
1
2
4
julia> bb[1:2] = zeros(Int64, 2)
2-element Vector{Int64}:
0
0
julia> aa
3-element Vector{Int64}:
0
0
4
julia> bb[3] = 88 # Maybe simple indexed assignment is different?
88
julia> aa
3-element Vector{Int64}:
0
0
88