Fill behaves this way not because of a specific design choice based on a
compelling use case, but because of consistency with other language
features. fill does not copy, and arrays are passed by reference in
Julia, consequently you have the behavior described below.

IMO it is best to learn about this and internalize the fact that arrays
and structures are passed by reference. The alternative would be some
DWIM-style solution where fill tries to figure out whether to copy its
first argument or not, which would be a mess.

On Tue, Sep 13 2016, Michele Zaffalon wrote:

> I have been bitten by this myself. Is there a user case for having an array
> filled with references to the same object? Why would one want this
> behaviour?
>
> On Tue, Sep 13, 2016 at 4:45 AM, Yichao Yu <yyc1...@gmail.com> wrote:
>
>>
>>
>> On Mon, Sep 12, 2016 at 10:33 PM, Zhilong Liu <lzl200102...@gmail.com>
>> wrote:
>>
>>> Hello all,
>>>
>>> I am pretty new to Julia, and I am trying to perform push and pop inside
>>> an array of 1D array elements. For example, I created the following array
>>> with 1000 empty arrays.
>>>
>>> julia> vring = fill([], 1000)
>>>
>>
>>
>> This creates an array with 1000 identical object, if you want to make them
>> different (but initially equal) object, you can use `[[] for i in 1:1000]`
>>
>>>
>>> Then, when I push an element to vring[2],
>>>
>>>
>>> julia> push!(vring[2],1)
>>>
>>>
>>> I got the following result. Every array element inside vring gets the
>>> value 1. But I only want the 1 to be pushed to the 2nd array element
>>> inside vring. Anybody knows how to do that efficiently?
>>>
>>>
>>> julia> vring
>>>
>>> 1000x1 Array{Array{Any,1},2}:
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  ⋮
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>  Any[1]
>>>
>>>
>>>
>>> Thanks!
>>>
>>> Zhilong Liu
>>>
>>>
>>>
>>>
>>

Reply via email to