解构 (Destructuring)

Zig 支持对数组(Arrays)和元组(Tuples)进行解构。

数组解构

const std = @import("std");
const expect = std.testing.expect;

test "destructuring array" {
    const array = [_]u8{ 1, 2, 3 };
    const x, const y, const z = array;
    try expect(x == 1);
    try expect(y == 2);
    try expect(z == 3);
}

元组解构

const std = @import("std");
const expect = std.testing.expect;

test "destructuring tuple" {
    const tuple = .{ 1, 2, 3 };
    const x, const y, const z = tuple;
    try expect(x == 1);
    try expect(y == 2);
    try expect(z == 3);
}

忽略值

你可以使用 _ 来忽略你不想要的值:

test "destructuring with ignored values" {
    const array = [_]u8{ 1, 2, 3 };
    const x, _, const z = array;
    try expect(x == 1);
    try expect(z == 3);
}

另请参阅: