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.

function zeroval(ival::Int)
    ival = 0
end

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.

function zeroptr(iptr::Ref{Int})
    iptr[] = 0
end

Now let’s see how these functions are used:

function main()
    i = 1
    println("initial:", i)

    zeroval(i)
    println("zeroval:", i)

    # The Ref(i) syntax creates a reference to i
    zeroptr(Ref(i))
    println("zeroptr:", i)

    # References can be printed too
    println("reference:", Ref(i))
end

main()

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:

initial: 1
zeroval: 1
zeroptr: 0
reference: Base.RefValue{Int64}(0)

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.