What a reference is
The ^ operator, written after a variable, creates a reference to that variable. A reference and the variable it points to share the same storage. Write through the reference, and the original variable changes too.
def main() -> Int32
x: Int32 = 10
r: Int32 = x^
print(r)
r += 5
print(r)
print(x)
return 0
Changing r changed x. They are the same slot now.
How to create one
Write a variable's name followed by ^, and assign it to a new variable of the same type:
r: Int32 = x^
The reference takes on the value the variable holds at that moment, and stays linked to it from then on.
Rules
- A reference must point at a variable.
x^wherexis a variable is fine.5^or(a + b)^is a compile error. - The reference has the same type as the variable it points at.
- Chains of references are fine. You can take a reference to a reference.
- Cycles are not allowed.
Why you'd use one
References let you update a variable through another name, and plain = works through them too. So while reassignment is available for local variables, ^ is the way to change a variable that lives somewhere else — from a nested call or a shared slot.
Because the reference shares storage, updating it updates the original everywhere it's used. The pointer example in the repo plays with this idea.