Learning Zig from the official language reference.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
zig-langref/slices.zig

58 lines
1.8 KiB

const std = @import("std");
const fmt = std.fmt;
const debug = std.debug;
const testing = std.testing;
test "basic slices" {
var array = [_]i32{ 1, 2, 3, 4, 5 };
debug.print("{s}\n", .{@typeName(@TypeOf(array))});
// since its indices are known at comptime, this is actually a pointer to an array, but this coerces into
// a slice
const slice1 = array[0..];
debug.print("{s}\n", .{@typeName(@TypeOf(slice1))});
testing.expectEqual(@TypeOf(slice1), @TypeOf(&array));
// this is a proper slice since its indices are known only at runtime
var runtime_index_zero: usize = 0;
const slice = array[runtime_index_zero..array.len];
debug.print("{s}\n", .{@typeName(@TypeOf(slice))});
testing.expectEqual(@TypeOf(slice), []i32);
testing.expectEqual(slice.len, array.len);
for (array) |elem, idx| {
testing.expectEqual(elem, slice[idx]);
}
// this is a multi-item pointer
testing.expectEqual(@TypeOf(slice.ptr), [*]i32);
testing.expectEqual(@TypeOf(&slice[0]), *i32);
}
test "using slices for strings" {
const hello: []const u8 = "hello";
const world: []const u8 = "世界";
debug.print("len of hello = {}, len of world = {}\n", .{ hello.len, world.len });
var all_together: [100]u8 = undefined;
const hello_world = try fmt.bufPrint(all_together[0..], "{s}, {s}", .{ hello, world });
debug.print("{s}\n", .{hello_world});
}
test "slice pointer" {
var array: [10]u8 = undefined;
const ptr = &array;
const slice = ptr[0..5];
slice[2] = 3;
testing.expectEqual(slice.len, 5);
testing.expectEqual(array[2], 3);
testing.expectEqual(@TypeOf(slice), *[5]u8);
}
test "sentinel-terminated slices" {
const slice: [:0]const u8 = "hello";
testing.expectEqual(slice.len, 5);
testing.expectEqual(slice[slice.len], 0);
}