我在Julia遇到绑定问题
尝试这样做时:
type Chain
value :: Int
son :: Chain
#Make the last link in the chain point to itself
#so as to spare us from the julia workaround for nulls
Chain(value::Int) = (chain = new(); chain.value = value; chain.son = chain; chain)
end
#Create three separate nodes
c=Chain(5)
d=Chain(2)
e=Chain(1)
#Link an object to another and then modify the linked object
c.son = d
son = d.son
son = e
c
我想更改父级中儿子的链接,但只有在我执行此操作时才有效:
c.son = d
d.son = e
c
这会在递归函数中产生问题,如果将对象传递给链接到另一个对象的函数并在函数体中更改它,则链接不会更改,只会更改对象本身.
我尝试过使用julia函数pointer_from_objref,但这用于处理c函数和使用unsafe_store进行赋值!没用.
我如何创建一个变量,当分配给它时也改变我所指的链接?
最佳答案 如果我理解你的属性,你可以将son声明为Array => son :: Array {Chain,1}来实现这一点.
type Chain
value::Int
son::Array{Chain,1}
Chain(value::Int) = (chain = new(); chain.value = value; chain.son = [chain]; chain)
end
julia> c=Chain(5)
Chain(5,[Chain(#= circular reference =#)])
julia> d=Chain(2)
Chain(2,[Chain(#= circular reference =#)])
julia> e=Chain(1)
Chain(1,[Chain(#= circular reference =#)])
julia> c.son = [d]
1-element Array{Chain,1}:
Chain(2,[Chain(#= circular reference =#)])
julia> son = d.son
1-element Array{Chain,1}:
Chain(2,[Chain(#= circular reference =#)])
julia> son[:] = e
Chain(1,[Chain(#= circular reference =#)])
julia> c
Chain(5,[Chain(2,[Chain(1,[Chain(#= circular reference =#)])])])
这是因为通过运行son = d.son和son = e,您只需完全更改绑定.
# NOT using array type
julia> son = d.son
Chain(2,Chain(#= circular reference =#))
julia> son = e
Chain(1,Chain(#= circular reference =#))
julia> son === d.son
false
# using array type
julia> son = d.son
1-element Array{Chain,1}:
Chain(2,[Chain(#= circular reference =#)])
julia> son[:] = e
Chain(1,[Chain(#= circular reference =#)])
julia> son === d.son
true
如果要保留链接,解决方法是使用数组类型并更改数组的内容而不是其绑定. more details about bindings.