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

可选类型体现了 Zig 如何在不牺牲效率或可读性的前提下提供安全性。

问号表示可选类型。在一个类型前加问号,就能将其变为可选类型,例如:

optional_integer.zig
// 普通整数
const normal_int: i32 = 1234;
// 可选整数
const optional_int: ?i32 = 5678;

现在变量 optional_int 可以是 i32,也可以是 null。

下面暂不讨论整数,转而讨论指针。空引用是许多运行时异常的来源,甚至被指责为计算机科学最严重的错误。

Zig 没有这种空引用。

可以改用可选指针。它在底层会编译为普通指针,因为可以使用 0 表示可选类型的空值。与此同时,编译器会检查代码,确保不会将空值赋给不允许为空的对象。

不允许普通空值通常会使代码更冗长,但可以比较以下功能等价的 C 代码和 Zig 代码。

任务:调用 malloc,若结果为空,则返回空值。

C 代码

call_malloc_in_c.c
// malloc prototype included for reference
void *malloc(size_t size);
struct Foo *do_a_thing(void) {
char *ptr = malloc(1234);
if (!ptr) return NULL;
// ...
}

Zig 代码

call_malloc_from_zig.zig
// 列出 malloc 原型以供参考
extern fn malloc(size: usize) ?[*]u8;
fn doAThing() ?*Foo {
const ptr = malloc(1234) orelse return null;
_ = ptr; // ...
}

此处 Zig 至少与 C 同样方便,甚至可能更方便。此外,"ptr" 的类型为 [*]u8,而不是 ?[*]u8。orelse 关键字解包了可选类型,因此保证函数中所有使用 ptr 的位置都非空。

另一种常见的 NULL 检查写法如下:

checking_null_in_c.c
void do_a_thing(struct Foo *foo) {
// do some stuff
if (foo) {
do_something_with_foo(foo);
}
// do some stuff
}

在 Zig 中可以完成同样的操作:

checking_null_in_zig.zig
const Foo = struct {};
fn doSomethingWithFoo(foo: *Foo) void {
_ = foo;
}
fn doAThing(optional_foo: ?*Foo) void {
// 执行一些操作
if (optional_foo) |foo| {
doSomethingWithFoo(foo);
}
// 执行一些操作
}

再次注意,if 块内的 foo 已不再是可选指针,而是不能为 null 的普通指针。

这一点的好处是,可以为接收指针参数的函数标注 "nonnull" 属性,即 GCC 中的 __attribute__((nonnull))。知道指针参数不可能为空,有时能帮助优化器做出更好的决策。

可选类型

在类型前加上 ? 即可创建可选类型。可以使用编译时反射访问其子类型:

test_optional_type.zig
const expectEqual = @import("std").testing.expectEqual;
test "optional type" {
// 声明可选值,并从 null 强制转换:
var foo: ?i32 = null;
// 从可选类型的子类型强制转换
foo = 1234;
// 使用编译时反射访问可选类型的子类型:
try comptime expectEqual(i32, @typeInfo(@TypeOf(foo)).optional.child);
}
命令行
$ zig test test_optional_type.zig
1/1 test_optional_type.test.optional type...OK
All 1 tests passed.

null

与 undefined 一样,null 具有自己的类型,只能通过转换为其他类型来使用:

null.zig
const optional_value: ?i32 = null;

可选指针

可选指针保证与普通指针大小相同。可选值的 null 保证表示地址 0。

test_optional_pointer.zig
const expectEqual = @import("std").testing.expectEqual;
test "optional pointers" {
// 普通指针不能为 null。如需空指针,应使用可选前缀
// `?` 将指针类型变为可选类型。
var ptr: ?*i32 = null;
var x: i32 = 1;
ptr = &x;
try expectEqual(1, ptr.?.*);
// 可选指针与普通指针大小相同,因为使用指针值
// 0 来表示空值。
try expectEqual(@sizeOf(?*i32), @sizeOf(*i32));
}
命令行
$ zig test test_optional_pointer.zig
1/1 test_optional_pointer.test.optional pointers...OK
All 1 tests passed.

另见: