两个结构可以互相引用吗?-朱莉娅



我有一个结构,它包含一个相同类型的字段,在创建时无法分配。茱莉亚似乎不喜欢下面这些。(它发出了一个循环参考投诉。(我打算把问题归结为的本质

mutable struct Test
test:: Union{Test,Nothing}
end
t1 = Test(nothing)
t2 = Test(nothing)
t1.test = t2
t2.test = t1
  1. 实现这一目标的正确方法是什么?(例如,我怎么能指我的伴侣,谁能指我作为他的伴侣?(
  2. 另外,上述目前的正确方式是否有一个初步的";空";字段

您提出的是一种初始nothing字段的正确方法。

或者,你可以做一些类似的事情:

julia> mutable struct Test
test::Test
Test(t::Test) = new(t)
Test() = new()
end
julia> t1 = Test()
Test(#undef)
julia> t2 = Test()
Test(#undef)
julia> t1.test = t2
Test(#undef)
julia> t2.test = t1
Test(Test(Test(#= circular reference @-2 =#)))

其中您有临时#undef字段。

另请参阅《Julia手册》的"初始化不完整"部分。

编辑

使用标准Vector{Any}:的循环参考示例

julia> x = Any[]
Any[]
julia> push!(x, x)
1-element Vector{Any}:
1-element Vector{Any}:#= circular reference @-1 =#

最新更新