Why is Ref() not reflecting the changes

Hello I am playing with the Ref{T} and I cannot understand why when doing some updates the changes are visible via the variable holding the Ref and when doing other updates they don’t show up. I would appreciate your help thank you :smiley:.

mutable struct CommBoard
    orders::Array{Int,1}

    function CommBoard()
        new(Array{Int,1}([]))
    end
end

comm = CommBoard()
comm.orders = [20,35]
mycomm = Ref(comm)

function init_comm(comm::CommBoard)
    comm.orders = []
    return nothing
end

init_comm(comm)
println(comm) #returns CommBoard(Int64[])
println(mycomm[]) #returns CommBoard(Int64[])

comm.orders = [20,35]
println(comm) #returns CommBoard(Int64[20,35])
println(mycomm[]) #returns CommBoard(Int64[])

If I just copy paste your code into the REPL I get what you (and I) would expect, not what you wrote:

julia> mutable struct CommBoard
           orders::Array{Int,1}

           function CommBoard()
               new(Array{Int,1}([]))
           end
       end

julia> comm = CommBoard()
CommBoard(Int64[])

julia> comm.orders = [20,35]
2-element Vector{Int64}:
 20
 35

julia> mycomm = Ref(comm)
Base.RefValue{CommBoard}(CommBoard([20, 35]))

julia> function init_comm(comm::CommBoard)
           comm.orders = []
           return nothing
       end
init_comm (generic function with 1 method)

julia> init_comm(comm)

julia> println(comm) #returns CommBoard(Int64[])
CommBoard(Int64[])

julia> println(mycomm[]) #returns CommBoard(Int64[])
CommBoard(Int64[])

julia> comm.orders = [20,35]
2-element Vector{Int64}:
 20
 35

julia> println(comm) #returns CommBoard(Int64[20,35])
CommBoard([20, 35])

julia> println(mycomm[]) #returns CommBoard(Int64[])
CommBoard([20, 35])
2 Likes

Thank I just restarted the Julia instance and it works as expected after I isolate I think another piece of code is interfering with it. Because It is not a a real problem I will just delete the post as I don’t see any value from it. Thank you very much for your response. (Like the reply so I can delete the post)

1 Like