Can two structs reference each other? - Julia

Viewed 67

I have a struct that includes a field of the same type, which I cannot assign at creation. Julia does not seem to like the following. (It coughs up a circular reference complaint.) I intend this to boil the problem down to its essentials

mutable struct Test
    test:: Union{Test,Nothing}
end
t1 = Test(nothing)
t2 = Test(nothing)
t1.test = t2
t2.test = t1
  1. What is the right way to achieve this? (E.g., how can I point to my partner, who can point to me as his partner?)
  2. Separately, is the above currently the right way to have an initially "null" field?
1 Answers

What you propose is a correct way to have initially nothing field.

Alternatively you can do something like:

julia> mutable struct Test
           test::Test
           Test(t::Test) = new(t)
           Test() = new()
       end

julia> t1 = Test()
Test(#undef)

julia> t2 = Test()
Test(#undef)

julia> t1.test = t2
Test(#undef)

julia> t2.test = t1
Test(Test(Test(#= circular reference @-2 =#)))

where you have temporarily #undef field.

See also Incomplete Initialization section of the Julia Manual.

Edit

An example of circular reference with a standard Vector{Any}:

julia> x = Any[]
Any[]

julia> push!(x, x)
1-element Vector{Any}:
 1-element Vector{Any}:#= circular reference @-1 =#
Related