朱莉娅:循环引用

3

我该如何解决这个问题?

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

会产生一个错误

加载错误:未定义变量错误:Child未定义

有没有办法处理这种情况?


相互递归类型仍然是该语言中的一个[未解决问题]。 - phipsgabler
请返回翻译后的文本。 - phipsgabler
2个回答

7
据我所知,目前唯一处理这个问题的方式是通过参数类型(我知道它并不完美)。下面是一个例子,还限制了参数类型,以便您几乎得到想要的结果:
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")

可能你也想用刚创建的parent实例化childchild = Child("son", parent),然后使用push!(parent.children, child)child添加到parent.children中。 - Ben Francis

0
只是为了补充@Bogumił Kamiński的答案,抽象类型AbstractChild end在程序运行时创建了一个节点,供Julia遍历。

1
这应该是对Bogumil答案的评论,而不是一个单独的答案。 - ehambright

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接