test_basic_slices.zig (2279B) - Raw
1 const expect = @import("std").testing.expect; 2 const expectEqualSlices = @import("std").testing.expectEqualSlices; 3 4 test "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 expect(@TypeOf(slice) == []i32); 16 try expect(&slice[0] == &array[0]); 17 try expect(slice.len == array.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 expect(@TypeOf(array_ptr) == *[array.len]i32); 23 24 // You can perform a slice-by-length by slicing twice. This allows the compiler 25 // to perform some optimisations like recognising a comptime-known length when 26 // the start position is only known at runtime. 27 var runtime_start: usize = 1; 28 _ = &runtime_start; 29 const length = 2; 30 const array_ptr_len = array[runtime_start..][0..length]; 31 try expect(@TypeOf(array_ptr_len) == *[length]i32); 32 33 // Using the address-of operator on a slice gives a single-item pointer. 34 try expect(@TypeOf(&slice[0]) == *i32); 35 // Using the `ptr` field gives a many-item pointer. 36 try expect(@TypeOf(slice.ptr) == [*]i32); 37 try expect(@intFromPtr(slice.ptr) == @intFromPtr(&slice[0])); 38 39 // Slices have array bounds checking. If you try to access something out 40 // of bounds, you'll get a safety check failure: 41 slice[10] += 1; 42 43 // Note that `slice.ptr` does not invoke safety checking, while `&slice[0]` 44 // asserts that the slice has len > 0. 45 46 // Empty slices can be created like this: 47 const empty1 = &[0]u8{}; 48 // If the type is known you can use this short hand: 49 const empty2: []u8 = &.{}; 50 try expect(empty1.len == 0); 51 try expect(empty2.len == 0); 52 53 // A zero-length initialization can always be used to create an empty slice, even if the slice is mutable. 54 // This is because the pointed-to data is zero bits long, so its immutability is irrelevant. 55 } 56 57 // test_safety=index out of bounds