Reputation: 4016
In Julia (0.3.0-rc1), when I fill
an array with instances of a composite type and update a member of a single instance, all instances in the array get updated. Is this the intended behaviour and, if so, how should I change the value of just a single element in the array?
The code in question:
type Foo
x :: Int
y :: Int
end
arr = fill(Foo(2, 4), 3)
arr[2].x = 5
I expect [Foo(2, 4), Foo(5, 4), Foo(2, 4)]
but instead I get [Foo(5, 4), Foo(5, 4), Foo(5, 4)]
. What am I doing wrong? Should I always update the entire element, as in arr[2] = Foo(5, 4)
(which gives the expected results)? TIA.
Upvotes: 3
Views: 166
Reputation: 11664
You created one instance of Foo
and filled the array with references to this one instance.
You probably want arr = [Foo(2,4) for i in 1:3]
which will create a new copy of Foo(2,4)
for every index`.
Upvotes: 3