Search code examples
arraysrecordjulia

Modifying member values of composite types in an array


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.


Solution

  • 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`.