朱莉娅:循环参考

时间:2019-06-02 18:20:36

标签: 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)

    end

end

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

产生错误

  

LoadError:UndefVarError:未定义子对象

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

2 个答案:

答案 0 :(得分:1)

据我所知,当前处理此问题的唯一方法是通过参数类型(我知道它并不完美)。这是另外一个限制参数的示例,以便您几乎可以得到所需的内容:

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")

答案 1 :(得分:0)

为了补充@Bogumił Kamiński 的回答,抽象类型 AbstractChild 端创建了一个节点,供 julia 在程序运行时从中遍历。