Pointers
A pointer holds the memory address of a value. The type ^T is a pointer to a T value. Its zero value is nil.
p: ^int;
The & operator takes the address of its operand.
i := 1337;
p = &i;
The ^ operator also dereferences the pointer to reveal its underlying value.
fmt.println(p^); // read `i` through the pointer `p`
p^ = 9001; // write `i` through the pointer `p`
Note: This syntax may seem uncommon to C programmers but here's a mnemonic to help remember:
x^-xfrom pointer^T- pointer to typeT&x- address fromx
Pointer Arithmetic
Odin supports pointer arithmetic.
array := [4]int{1, 2, 3, 4};
p := &array[0]; // Take the pointer to the first element
i := (p + 2)^;
fmt.println(i); // Prints `3`
q := &array[2];
distance := q - p;
fmt.println(distance); // Prints `2`
rawptr
rawptr is a special pointer type that cannot be deferenced nor have pointer arithmetic. All pointers can be implicitly converted to a rawptr. A rawptr cannot be implicity converted to any other pointer type.
i := 123;
p: rawptr = &i;
x := p + 1; // Error: Pointer arithmetic is not supported for a `rawptr`
y := p^; // Error: A `rawptr` cannot be deferenced