Data Layout

Good day!

I’m trying to come up with the best data layout using structs for the following situation. I have a struct

mutable struct MyStruct
   field1::Float64
   field2::String
end

From this struct I would like to link other structs of various types, let’s call them layers. The number of linked structs can vary. My thoughts is that I could link this via adding for example a Tuple (or named Tuple) which links to the structs, i.e

mutable struct MyStruct
   field1::Float64
   field2::String
   layers::Tuple
end

I could also use for example an Array or a Dict but it seems that Tuple plays well with the StructArrays package. One problem I have with using a Tuple is that there doesn’t seem that a Tuple can have 0 or 1 element? I have tried searching for an answer to this, but no luck.

So all in all I have two questions.

1, Is it possible to have Tuples with 0 or 1 element?
2, Is there a better way to set up the kind of data structure that I want to have?

Thanks! /Robin

To really answer your question well, you would have to explain a bit more, how exactly you want to use the field layers, is the type and number of objects stored in layers always known when MyStruct is created or is it allowed to be changed afterwards. In the first case I would make the type of layers a type parameter and would have nothing represent the 0-element case and Some(x) the 1-element case. This is what it could look like:

mutable struct MyStruct{T<:Union{Nothing,Some}}
   field1::Float64
   field2::String
   layer::T
   MyStruct(field1, field2) = new{Nothing}(field1, field2, nothing)
   MyStruct(field1, field2, layer::T) where T = new{Some{T}}(field1, field2, Some(layer))
end

If you want to store multiple objects of arbitrary type even after MyStruct has been created though, your best bet is probably just using a vector with element type Any, which will bring with it a performance penalty, but since it’s not possible to make that case type stable, you’re probably not going to get rid of that overhead anyways.

2 Likes