[docs] add examples of array/slice init using result location

This commit is contained in:
Pyrolistical 2024-05-07 11:00:42 -07:00 committed by Andrew Kelley
parent f71f27bcb0
commit cb77bd672c
2 changed files with 14 additions and 0 deletions

View File

@ -5,6 +5,13 @@ const mem = @import("std").mem;
// array literal
const message = [_]u8{ 'h', 'e', 'l', 'l', 'o' };
// alternative initialization using result location
const alt_message: [5]u8 = .{ 'h', 'e', 'l', 'l', 'o' };
comptime {
assert(mem.eql(u8, &message, &alt_message));
}
// get the size of an array
comptime {
assert(message.len == 5);

View File

@ -1,10 +1,17 @@
const expect = @import("std").testing.expect;
const expectEqualSlices = @import("std").testing.expectEqualSlices;
test "basic slices" {
var array = [_]i32{ 1, 2, 3, 4 };
var known_at_runtime_zero: usize = 0;
_ = &known_at_runtime_zero;
const slice = array[known_at_runtime_zero..array.len];
// alternative initialization using result location
const alt_slice: []const i32 = &.{ 1, 2, 3, 4 };
try expectEqualSlices(i32, slice, alt_slice);
try expect(@TypeOf(slice) == []i32);
try expect(&slice[0] == &array[0]);
try expect(slice.len == array.len);