Pointers
A pointer points to another value:
const std = @import("std");
const expect = std.testing.expect;
test "using a pointer" {
// Use & to get a pointer to a variable.
const a: u64 = 5;
const ptr = &a;
try expect(@TypeOf(ptr) == *const u64);
// Dereference the pointer with .*
const b = ptr.*;
try expect(b == 5);
}
test "using a pointer to change a value" {
// If a pointer points to a mutable variable, we can
// use it to change the value.
var a: u64 = 5;
const ptr = &a;
try expect(@TypeOf(ptr) == *u64);
try expect(ptr.* == 5);
ptr.* = 6;
try expect(a == 6);
}
test "pointer to array element" {
// A pointer can point into another data structure,
// for example to an array element.
var a = [_]u64{ 1, 2, 3 };
const ptr = &a[1];
ptr.* = 22;
try expect(a[1] == 22);
}
test "changing a pointer" {
// If the pointer itself is mutable, we can change
// it to point somewhere else.
const a: u64 = 5;
const b: u64 = 7;
var ptr = &a;
try expect(ptr.* == 5);
ptr = &b;
try expect(ptr.* == 7);
}$ zig test pointers.zig
All 4 tests passed.
Next example: Optionals.