Behaviour of Ref?

Hello everybody,

I am trying to use Ref to change a variable, and it does not work as expected (at least, as I expected).

julia> a = 5
5

julia> typeof(a)
Int64

julia> b = Ref(a)
Base.RefValue{Int64}(5)

julia> typeof(b)
Base.RefValue{Int64}

julia> b[] = 10
10

julia> b
Base.RefValue{Int64}(10)

julia> a
5

I believed that changing b the variable a should be changed. I think previously it was working in that way, but now it does not.

I actually does not use directly Ref, but I try to change results of a package in Python that uses PyCall (pysr). In a previous version, I could change the internal structure (using small functions in Julia) but now it is not working now, it is like it was a copy. Studying that I come to this expected (for me) behaviour.

Could anyone confirm this is working as expected?

Thank a lot.

Yes, this behavior is expected. Two keywords to look into are mutation and assignment (see for example Assignment and mutation - #4 by StefanKarpinski).

I will add comments to describe:

julia> a = 5 # assign the name `a` to point to the value 5
5

julia> typeof(a)
Int64

julia> b = Ref(a) # assign the name `b` to the value `Ref(a)` which is the exact same thing as `Ref(5)`
Base.RefValue{Int64}(5)

julia> typeof(b)
Base.RefValue{Int64}

julia> b[] = 10 # mutate the contents of `b` to be 10, i.e. perform `setindex!(b, 10)`. 
10

julia> b # observe `b` with its updated contents
Base.RefValue{Int64}(10)

julia> a # the name `a` points to the same, unmutated value, 5, since that value has never been touched
5

Note that Refs are like any other container; they contain values, and you can change their contents by mutating them.

5 Likes