Hi all,
I am having trouble defining simple structs and I would like your help!
The main issue is how to define a pointer to a struct of type Inner
inside a struct of type Outer
. So, the first idea is pretty obvious and looks like:
struct Inner
i::Int64
j::Int64
end
struct Outer
u::Inner
w::Int64
end
However, this approach leads to an initialization of Outer
that needs an initialization of Inner
:
obj = Outer(Inner(1, 2), 3)
In my case, I would like to initialize Outer
objects without knowing the parameters that initialize the Inner
object. To do this, the first idea it comes to my mind is making Outer
mutable and changing its u
parameter type to include Nothing
:
mutable struct Outer
u::Union{Inner,Nothing}
w::Int64
end
So now, we can initialize using:
obj = Outer(nothing, 3)
And change the value of the Inner
parameter later (once we know its parameters):
obj.u = Inner(1, 2)
But those two changes that I had to do (i.e. make the struct mutable and include the Nothing
type) don’t look elegant to me. I would rather prefer to use a similar approach than C: use a pointer to a struct Inner
inside Outer
. This pointer can point to NULL
meaning that it was not initialized or it can point to a struct of type Inner
.
How can I achieve such behavior? Remember, I would like to keep the Outer struct immutable.
Maybe, one idea is to use a Vector
. So let’s try it:
struct Outer
u::Vector{Inner}
v::Int64
end
and initialize using:
obj = Outer(Vector{Inner}(undef, 0), 3)
or, equivalently:
obj = Outer(Inner[], 3)
Later, I can push! an element:
push!(obj.u, Inner(1,2))
Is this the correct approach or there is a better one? Please, we aware that using a Vector{Inner}
for u
achieves the behavior of a list in C.
Thanks in advance!
Ramiro.