Inititializing a Vector of Structs

How to initialize a vector of structs in Julia

Published

March 14, 2024

Here’s an example of how to initialize a vector of structs in Julia. It’s sometimes useful to coerce other data structures into vectors of structs to perform operations on them, and so this snippet provides a basic example of creating and populating a vector of a custom struct

Load Pkgs and Define Struct

using Random #for creating data

#define struct
mutable struct MyType
  x::String
  y::Int64
  z::Vector{Float64}
end

#instantiate an example struct
a = MyType("hello", 1, [1., 1.5, 104.1])
MyType("hello", 1, [1.0, 1.5, 104.1])

Create a Constructor

This isn’t strictly necessary, but it can be useful. This just creates a new instance of MyType with random values

function MyType()
    MyType(randstring(10), rand(1:100), rand(Float64, 3))
end

a = MyType()
MyType("WAc1LBvkFm", 33, [0.3619946274985777, 0.858479824777187, 0.720193448993144])

Create an Empty n-vector, then Populate It

n = 100

#initialize an n-vector with 0 values
v = Vector{MyType}(undef, n)

#populate the vector
for i  eachindex(v)
    v[i] = MyType()
end

Check Results

we want v to be a vector of MyType

typeof(v)
Vector{MyType} (alias for Array{MyType, 1})

and we want each element to be MyType

typeof(v[1])
MyType

and let’s check the first element

v[1]
MyType("HmSiEUvtnk", 24, [0.22658234942156086, 0.5284152678374769, 0.48072129238569283])