How to place an array as one of the fields of a mutable struct

I’m a beginner. I’m trying to create a mutable struct with three Float64 fields and one Array of three Float64s. Is there a way to do this, and what is the format.

1 Like

Have you read through Types · The Julia Language? Any specific questions you have after reading it?

1 Like

Are you just confused about how to specify the type of the Array? The Array type included in Base does not encode information about how many elements it has in the type, so you would declare your struct like

mutable struct S
    x::Float64
    y::Float64
    z::Float64
    arr::Vector{Float64} # alias for Array{Float64,1}
end

and in the constructor S(...) you would size arr to hold three elements.

If you want a statically sized array that always has three elements, you want to use the package StaticArrays (which should really be a stdlib imo, but I digress…). A mutable vector with a fixed size can be specified using an MVector{N, T}. Using StaticArrays your struct is:

using StaticArrays

mutable struct S
    x::Float64
    y::Float64
    z::Float64
    arr::MVector{3, Float64}
end

SVector{N, T} has the same interface, but is not mutable. It is faster if it fits your use case because it does not have to be stored on the heap. Read the StaticArrays docs for other details.

7 Likes

Thank you for your answer. That is exactly what I was looking for. Thank you Again!

Glad it helped. I remember coming to Julia a few years ago (StaticArrays was FixedSizeArrays back then…) with mainly C programming experience, and being confused as to how one was supposed to create useful data structures without the equivalent of double x[3], etc.

Thanks, you saved me a lot of time! Have a great day.