Pointers in Julia
Julia supports references to values and records within your program, which are similar to pointers in other languages.
We’ll show how references work in contrast to values with two functions: zeroval
and zeroptr
. zeroval
has an Int
parameter, so arguments will be passed to it by value. zeroval
will get a copy of ival
distinct from the one in the calling function.
zeroptr
in contrast has a Ref{Int}
parameter, meaning that it takes a reference to an Int
. The iptr[]
syntax in the function body then dereferences the reference to access the current value. Assigning a value to a dereferenced reference changes the value at the referenced address.
Now let’s see how these functions are used:
zeroval
doesn’t change the i
in main
, but zeroptr
does because it has a reference to the memory location for that variable.
When you run this program, you’ll see output similar to this:
In Julia, references are implemented using the Ref
type, which serves a similar purpose to pointers in other languages. The Ref
type provides a way to create mutable containers for single values, which can be passed by reference.
Julia’s type system and memory management differ from lower-level languages, so the concept of pointers is abstracted away in most cases. However, the Ref
type provides similar functionality when needed.