跳转到内容
语言参考Zig 0.17.0官方原文

切片由指针和长度组成。数组与切片的区别在于:数组长度属于类型的一部分,在编译时已知;切片长度则在运行时已知。两者都可通过 len 字段访问长度。

test_basic_slices.zig
const expectEqual = @import("std").testing.expectEqual;
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];
// 使用结果位置的另一种初始化方式
const alt_slice: []const i32 = &.{ 1, 2, 3, 4 };
try expectEqualSlices(i32, slice, alt_slice);
try expectEqual([]i32, @TypeOf(slice));
try expectEqual(&array[0], &slice[0]);
try expectEqual(array.len, slice.len);
// 使用编译时已知的起止位置切片,结果是
// 指向数组的指针,而不是切片。
const array_ptr = array[0..array.len];
try expectEqual(*[array.len]i32, @TypeOf(array_ptr));
// 对切片使用取地址运算符,得到单项指针。
try expectEqual(*i32, @TypeOf(&slice[0]));
// 使用 `ptr` 字段,得到多项指针。
try expectEqual([*]i32, @TypeOf(slice.ptr));
try expectEqual(@intFromPtr(slice.ptr), @intFromPtr(&slice[0]));
// 切片具有数组边界检查。尝试访问越界元素时,
// 会触发安全检查失败:
slice[10] += 1;
// 注意,`slice.ptr` 不执行安全检查,而 `&slice[0]`
// 会断言切片满足 len > 0。
// 可以这样创建空切片:
const empty1 = &[0]u8{};
// 如果类型已知,可以使用此简写:
const empty2: []u8 = &.{};
try expectEqual(0, empty1.len);
try expectEqual(0, empty2.len);
// 零长度初始化始终可以用于创建空切片,即使切片可变。
// 因为指向的数据长度为零位,其不可变性无关紧要。
}
命令行
$ zig test test_basic_slices.zig
1/1 test_basic_slices.test.basic slices...thread 700490 panic: index out of bounds: index 10, len 4
/home/andy/src/zig/doc/langref/test_basic_slices.zig:32:10: 0x124e6b8 in test.basic slices (test_basic_slices.zig)
slice[10] += 1;
^
/home/andy/src/zig/lib/compiler/test_runner.zig:295:25: 0x1200951 in mainTerminal (test_runner.zig)
if (test_fn.func()) |_| {
^
/home/andy/src/zig/lib/compiler/test_runner.zig:74:28: 0x1200132 in main (test_runner.zig)
return mainTerminal(init);
^
/home/andy/src/zig/lib/std/start.zig:789:88: 0x11fc8cf in callMain (std.zig)
if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11fc2b1 in _start (std.zig)
asm volatile (switch (native_arch) {
^
error: the following test command terminated with signal ABRT:
/home/andy/src/zig/.zig-cache/o/2aeb962c99d47a840e7d71e9dace847f/test --seed=0xebb328f7

这是优先使用切片而非指针的原因之一。

test_slices.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
const mem = std.mem;
test "using slices for strings" {
// Zig 没有专门的字符串概念。字符串字面量是常量指针,
// 指向以 null 结尾的 u8 数组;按照约定,“字符串”参数
// 应当是采用 UTF-8 编码的 u8 切片。
// 此处将 *const [5:0]u8 和 *const [6:0]u8 强制转换为 []const u8
const hello: []const u8 = "hello";
const world: []const u8 = "世界";
var all_together: [100]u8 = undefined;
// 对数组使用至少有一个索引在运行时已知的切片语法,
// 可以将数组转换为切片。
var start: usize = 0;
_ = &start;
const all_together_slice = all_together[start..];
// 字符串拼接示例。
const hello_world = try mem.print(all_together_slice, "{s} {s}", .{ hello, world });
// 通常可以直接使用 UTF-8,无须关心某个值是否为
// 字符串。如果不需要处理单个字符,就不需要
// 解码。
try expectEqualStrings("hello 世界", hello_world);
}
test "slice pointer" {
var array: [10]u8 = undefined;
const ptr = &array;
try expectEqual(*[10]u8, @TypeOf(ptr));
// 数组指针可以像数组一样切片:
var start: usize = 0;
var end: usize = 5;
_ = .{ &start, &end };
const slice = ptr[start..end];
// 对可变指针进行切片,得到的切片也可变。
try expectEqual([]u8, @TypeOf(slice));
slice[2] = 3;
try expectEqual(3, array[2]);
// 同样,使用编译时已知索引切片,会得到另一个
// 指向数组的指针:
const ptr2 = slice[2..3];
try expectEqual(1, ptr2.len);
try expectEqual(3, ptr2[0]);
try expectEqual(*[1]u8, @TypeOf(ptr2));
}
命令行
$ zig test test_slices.zig
1/2 test_slices.test.using slices for strings...OK
2/2 test_slices.test.slice pointer...OK
All 2 tests passed.

另见:

按长度切片

虽然 Zig 只提供基于起止索引的切片语法,但可以连续切片两次来表达按长度切片的操作。

形式 [a .. a + b] 始终更适合写为 [a..][0..b],原因如下:

  • 切片在内存中表示为指针和长度。虽然语法上看似需要两倍操作,但实际机器码反而少一次减法。
  • 如果 a 在运行时已知而 b 在编译时已知,前者得到切片,后者则得到指向数组的单项指针。后者通常更安全,因为长度在编译时已知。
slicing_by_length.zig
const expectEqual = @import("std").testing.expectEqual;
test "example" {
var array = [_]i32{ 1, 2, 3, 4 };
var runtime_start: usize = 1;
_ = &runtime_start;
const length = 2;
const array_ptr_len = array[runtime_start..][0..length];
try expectEqual(*[length]i32, @TypeOf(array_ptr_len));
}
命令行
$ zig test slicing_by_length.zig
1/1 slicing_by_length.test.example...OK
All 1 tests passed.

哨兵终止切片

语法 [:x]T 表示一种切片,其长度在运行时已知,并保证长度对应的索引位置包含哨兵值。该类型不保证此前没有其他哨兵元素。哨兵终止切片允许访问索引 len 处的元素。

test_null_terminated_slice.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "0-terminated slice" {
const slice: [:0]const u8 = "hello";
try expectEqual(5, slice.len);
try expectEqual(0, slice[5]);
}
命令行
$ zig test test_null_terminated_slice.zig
1/1 test_null_terminated_slice.test.0-terminated slice...OK
All 1 tests passed.

也可以使用切片语法的变体 data[start..end :x] 创建哨兵终止切片,其中 data 是多项指针、数组或切片,x 是哨兵值。

test_null_terminated_slicing.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "0-terminated slicing" {
var array = [_]u8{ 3, 2, 1, 0, 3, 2, 1, 0 };
var runtime_length: usize = 3;
_ = &runtime_length;
const slice = array[0..runtime_length :0];
try expectEqual([:0]u8, @TypeOf(slice));
try expectEqual(3, slice.len);
}
命令行
$ zig test test_null_terminated_slicing.zig
1/1 test_null_terminated_slicing.test.0-terminated slicing...OK
All 1 tests passed.

哨兵终止切片操作会断言底层数据中哨兵位置的元素确实等于哨兵值。否则会导致带安全检查的非法行为。

test_sentinel_mismatch.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "sentinel mismatch" {
var array = [_]u8{ 3, 2, 1, 0 };
// 从数组创建长度为 2 的哨兵终止切片,
// 会使值 `1` 位于哨兵元素位置。
// 它与指定的哨兵值 `0` 不匹配,因而会导致
// 运行时 panic。
var runtime_length: usize = 2;
_ = &runtime_length;
const slice = array[0..runtime_length :0];
_ = slice;
}
命令行
$ zig test test_sentinel_mismatch.zig
1/1 test_sentinel_mismatch.test.sentinel mismatch...thread 708144 panic: sentinel mismatch: expected 0, found 1
/home/andy/src/zig/doc/langref/test_sentinel_mismatch.zig:13:24: 0x124c61f in test.sentinel mismatch (test_sentinel_mismatch.zig)
const slice = array[0..runtime_length :0];
^
/home/andy/src/zig/lib/compiler/test_runner.zig:295:25: 0x1200951 in mainTerminal (test_runner.zig)
if (test_fn.func()) |_| {
^
/home/andy/src/zig/lib/compiler/test_runner.zig:74:28: 0x1200132 in main (test_runner.zig)
return mainTerminal(init);
^
/home/andy/src/zig/lib/std/start.zig:789:88: 0x11fc8cf in callMain (std.zig)
if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11fc2b1 in _start (std.zig)
asm volatile (switch (native_arch) {
^
error: the following test command terminated with signal ABRT:
/home/andy/src/zig/.zig-cache/o/014b760bf6b184e3763ae97f78a686b6/test --seed=0xd8ed78c7

另见: