Julia 朱莉娅:循环引用

Julia 朱莉娅:循环引用,julia,Julia,如何解决这个问题 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)

如何解决这个问题

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")
产生错误

LoadError:UndevarError:未定义子级


有什么方法可以处理这种情况吗?

据我所知,目前处理这种情况的唯一方法是通过参数化类型(我知道它并不完美)。下面是一个额外限制参数的示例,这样您几乎可以得到您想要的:

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")
抽象类型AbstractChild-end

可变结构父对象{t交互递归类型在该语言中仍然是一个[未决问题]。()