What is Ref?

I am not sure why everyone adopted Ref for this, anything that acts as an scalar and encapsulates an arbitrary object will do. I, for an example, use single-element tuples instead of Ref, but this was just a question of personal taste. Now we have the situation in which Ref is used so much as a scalar container that people do not even know its reason to exist.

Ref is basically what would be a “pointer” in other languages. It is an object that just stores the memory position of another object, it may not be pointing anywhere (i.e., be empty) in which case it has a null value stored (which cannot be a valid memory address) and you can check if this is the case. They are much more relevant in languages with memory models different from Julia like C, for example, where assigning a struct to a local variable will copy every field in the struct at the right hand-side to the already preallocated struct on the left-hand side (and, as so, to manipulate some things without excessive copies you will need ); in Julia, the variable (which does not require any preallocation, i.e., it is just a label not a box) will now point to the exact same object as the right-side, and if it already contained something before, it is forgotten.

I have a kinda abstract post about the Julia memory model here: Is it appropriate to say a variable is a label or box? - #19 by Henrique_Becker
However, if you never programmed in a programming language with a different memory model the distinction may be lost on you.

7 Likes