Search code examples
julia

Julia: circular reference


how can is solve this problem?

mutable struct Parent
    name::String
    children::Vector{Child}

    function Parent(name)
        return new(name)

    end

end

mutable struct Child
    name::String
    parent::Parent

    function Child(name)
        return new(name)

    end

end

parent = Parent("father")
child = Child("son")

Produces an error

LoadError: UndefVarError: Child not defined

Is there some way to handle this case?


Solution

  • As far as I know the only way to handle this currently is via a parametric type (I know it is not perfect). Here is an example which additionally restricts the parameter so that you get almost what you want:

    abstract type AbstractChild end
    
    mutable struct Parent{T<:AbstractChild}
        name::String
        children::Vector{T}
        function Parent{T}(name) where {T<:AbstractChild}
            return new{T}(name)
        end
    
    end
    
    mutable struct Child <: AbstractChild
        name::String
        parent::Parent
    
        function Child(name)
            return new(name)
        end
    end
    
    Parent(name) = Parent{Child}(name)
    
    parent = Parent("father")
    child = Child("son")