#Initialise an ArrayList with appendNTimes with a struct that needs to be init'ed

1 messages · Page 1 of 1 (latest)

rain marsh
#

I was naively thinking I could do something like:

my_array.appendNTimesAssumeCapacity(MyStruct.init(allocator), 100);

But since I'm seeing some unexpected behaviour I now think it init's the struct once and then "shallow" copies it to all items (so if the struct has an array in it, they will all point to the same backing array).

Is that assumption correct? And if so is there a better way to fill the array, or should I resort to having to looping over each item?

brave burrow
#

yeah in that line you wrote there's no way for the arraylist to know it has to do something fancier than copying the bits inside MyStruct

#

it can't do something like call MyStruct.init 100 times, because the call occurs before any arraylist code is run. it doesn't know how the value you passed in was created

rain marsh
#

It looks like this (as described above) for arrays, but funny enough I also have a place where I do this where the struct has a HashMap in one of its field and that doesn give the same issue (it seems). At least it looks like they are not sharing the same backing memory.

But thinking about it, this is probably because each array is doing its own reallocation and from that moment on they have their own backing memory.

brave burrow
#

you could maybe do:

for (my_array.addManyAsSlice(100)) |*p| {
    p.* = MyStruct.init(allocator);
}

addManyAsSlice appends n undefined items to the arraylist and returns a slice of the new items; then you iterate over the slice using pointer capture so that you can replace each of the items with a correctly-created one

rain marsh
rain marsh
brave burrow
rain marsh
#

No, I fully understand that. I just didn't realise I was doing that here...

#

Thanks a million!!