1const expectEqual = @import("std").testing.expectEqual;
2const expectEqualSlices = @import("std").testing.expectEqualSlices;
3
4test "basic slices" {
5 var array = [_]i32{ 1, 2, 3, 4 };
6 var known_at_runtime_zero: usize = 0;
7 _ = &known_at_runtime_zero;
8 const slice = array[known_at_runtime_zero..array.len];
9
10 // alternative initialization using result location
11 const alt_slice: []const i32 = &.{ 1, 2, 3, 4 };
12
13 try expectEqualSlices(i32, slice, alt_slice);
14
15 try expectEqual([]i32, @TypeOf(slice));
16 try expectEqual(&array[0], &slice[0]);
17 try expectEqual(array.len, slice.len);
18
19 // If you slice with comptime-known start and end positions, the result is
20 // a pointer to an array, rather than a slice.
21 const array_ptr = array[0..array.len];
22 try expectEqual(*[array.len]i32, @TypeOf(array_ptr));
23
24 // Using the address-of operator on a slice gives a single-item pointer.
25 try expectEqual(*i32, @TypeOf(&slice[0]));
26 // Using the `ptr` field gives a many-item pointer.
27 try expectEqual([*]i32, @TypeOf(slice.ptr));
28 try expectEqual(@intFromPtr(slice.ptr), @intFromPtr(&slice[0]));
29
30 // Slices have array bounds checking. If you try to access something out
31 // of bounds, you'll get a safety check failure:
32 slice[10] += 1;
33
34 // Note that `slice.ptr` does not invoke safety checking, while `&slice[0]`
35 // asserts that the slice has len > 0.
36
37 // Empty slices can be created like this:
38 const empty1 = &[0]u8{};
39 // If the type is known you can use this short hand:
40 const empty2: []u8 = &.{};
41 try expectEqual(0, empty1.len);
42 try expectEqual(0, empty2.len);
43
44 // A zero-length initialization can always be used to create an empty slice, even if the slice is mutable.
45 // This is because the pointed-to data is zero bits long, so its immutability is irrelevant.
46}
47
48// test_safety=index out of bounds