Problem with array of structs

Hello everyone, I have the following problem:

Base.@kwdef struct s
    a = [0.0,0.0,0.0]

vec = fill(s(), 3)

for (indx,v) in enumerate(vec)
    v.a[1] = indx



3-element Vector{s}:
s([3.0, 0.0, 0.0])
s([3.0, 0.0, 0.0])
s([3.0, 0.0, 0.0])

But, I would expect it to return instead:

3-element Vector{s}:
s([1.0, 0.0, 0.0])
s([2.0, 0.0, 0.0])
s([3.0, 0.0, 0.0])

Anyone know how to help me? Thank you all so much in advance!

The problem is fill(). See this paragraph in the docs

Every location of the returned array is set to (and is thus === to) the value that was passed; this means that if the value is itself modified, all
elements of the filled array will reflect that modification because they’re still that very value. This is of no concern with fill(1.0, (5,5)) as
the value 1.0 is immutable and cannot itself be modified, but can be unexpected with mutable values like — most commonly — arrays. For example,
fill([], 3) places the very same empty array in all three locations of the returned vector:

1 Like

Thank you very much, reading the documentation well I solved it using:

vec = [s() for i in 0:3]

My bad, next time I’ll be more careful :slight_smile: :+1: