master
1const expect = @import("std").testing.expect;
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 expect(x_ptr.* == 1234);
10
11 // When you get the address of a const variable, you get a const single-item pointer.
12 try expect(@TypeOf(x_ptr) == *const i32);
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 expect(@TypeOf(y_ptr) == *i32);
18 y_ptr.* += 1;
19 try expect(y_ptr.* == 5679);
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 expect(@TypeOf(ptr) == *u8);
29
30 try expect(array[2] == 3);
31 ptr.* += 1;
32 try expect(array[2] == 4);
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 expect(@TypeOf(x_array_ptr) == *[1]i32);
43
44 // Coerce to many-item pointer:
45 const x_many_ptr: [*]i32 = x_array_ptr;
46 try expect(x_many_ptr[0] == 1234);
47}
48
49// test