1const expectEqual = @import("std").testing.expectEqual;
2
3test "address of syntax" {
4 // Get the address of a variable:
5 const x: i32 = 1234;
6 const x_ptr = &x;
7
8 // Dereference a pointer:
9 try expectEqual(1234, x_ptr.*);
10
11 // When you get the address of a const variable, you get a const single-item pointer.
12 try expectEqual(*const i32, @TypeOf(x_ptr));
13
14 // If you want to mutate the value, you'd need an address of a mutable variable:
15 var y: i32 = 5678;
16 const y_ptr = &y;
17 try expectEqual(*i32, @TypeOf(y_ptr));
18 y_ptr.* += 1;
19 try expectEqual(5679, y_ptr.*);
20}
21
22test "pointer array access" {
23 // Taking an address of an individual element gives a
24 // single-item pointer. This kind of pointer
25 // does not support pointer arithmetic.
26 var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
27 const ptr = &array[2];
28 try expectEqual(*u8, @TypeOf(ptr));
29
30 try expectEqual(3, array[2]);
31 ptr.* += 1;
32 try expectEqual(4, array[2]);
33}
34
35test "slice syntax" {
36 // Get a pointer to a variable:
37 var x: i32 = 1234;
38 const x_ptr = &x;
39
40 // Convert to array pointer using slice syntax:
41 const x_array_ptr = x_ptr[0..1];
42 try expectEqual(*[1]i32, @TypeOf(x_array_ptr));
43
44 // Coerce to many-item pointer:
45 const x_many_ptr: [*]i32 = x_array_ptr;
46 try expectEqual(1234, x_many_ptr[0]);
47}
48
49// test