【问题标题】:Julia: circular referenceJulia:循环引用
【发布时间】:2019-06-02 18:20:36
【问题描述】:

如何解决这个问题?

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: Child not defined

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

【问题讨论】:

  • 相互递归类型在语言中仍然是一个 [open issue]。

标签: julia


【解决方案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")

【讨论】:

    【解决方案2】:

    只是为了添加到@Bogumił Kamiński 的答案,抽象类型 AbstractChild end 为 julia 在程序运行时创建一个节点。

    【讨论】:

    • 这应该是对 Bogumil 答案的评论,而不是单独的答案。
    猜你喜欢
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 2020-06-09
    相关资源
    最近更新 更多