Add instantiation of object to vector

Hello, I have defined an object via a mutable struct and I would like to instantiate n of them into a vector. Ultimately, I’d like to refer two them as vector[i].

Here’s MWE:

mutable struct Foo
x :: Float64
y :: Float64
end

foos = Vector{Foo}

n = 3

for i in 1:3
foo = Foo(randn(), 0)
push!(foos, foo)
end

I’d like to reference x in the second foo instance as

foos[2].x

Thanks for looking!

You’ve defined foos as the type, not as an instance. You just need Vector{Foo}() instead:

julia> foos = Vector{Foo}()
0-element Array{Foo,1}

julia> for i in 1:3
       foo = Foo(randn(), 0)
       push!(foos, foo)
       end

julia> foos[2].x
0.7274441671361673
5 Likes

A simple syntax for an empty array of Foo is

Foo[].

1 Like