Hi, I have code with a custom struct with different data types
mutable struct myStruct
name::String = ""
id::Int = -1
....
# several more entries of varied types
....
end
I want to read a file and use several of these structs to capture the data in an accesible way. I do not know how many structs I will need at run-time. I want to read through the file, then add myStruct
structs to a stored_array
one at a time as I complete them. Something along the lines of
function add_element(stored_data::Array{myStruct}, new_data::myStruct)
push!(stored_data, new_data)
return stored_array
end
I have tried this, but I get an error that push!
is not defined for these types. If I try to get define a new version of push!
, my program does not use it. See these attempted definitions and error
# not all of these were used at the same time
stored_array = Array{myStruct}
stored_array = Array{myStruct, length} # where length is an Int
stored_array = Array{myStruct}(undef, length)
function push!(stored_array::Type{Array{myStruct}}, data::myStruct)
....
end
function push!(stored_array::Array{myStruct}, data::myStruct)
...
end
ERROR: LoadError: MethodError: no method matching push!(::Type{Array{myStruct}}, ::myStruct)
Closest candidates are:
push!(::Type{Vector{myStruct}}, ::myStruct) at C:\Users\qt\Desktop\Julia\code\Debug\decoder.jl:122
push!(::Vector{myStruct}, ::myStruct) at C:\Users\qt\Desktop\Julia\code\Debug\decoder.jl:116
I feel that I am missing something much simpler. I have seen posts suggesting that looping over the array to initialize it is the best way to go, but with that I am having trouble initializing the array correctly.
Could someone who is more familiar with the language help me here? I’m open to changing my flow if there is a more “Julia” way to handle this use case.