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

noreturn 是以下表达式的类型:

  • break
  • continue
  • return
  • unreachable
  • while (true) {}

一起解析类型时,例如 if 子句或 switch 分支,noreturn 类型与其他所有类型都兼容。例如:

test_noreturn.zig
fn foo(condition: bool, b: u32) void {
const a = if (condition) b else return;
_ = a;
@panic("do something with a");
}
test "noreturn" {
foo(false, 1);
}
命令行
$ zig test test_noreturn.zig
1/1 test_noreturn.test.noreturn...OK
All 1 tests passed.

noreturn 的另一个用例是 exit 函数:

test_noreturn_from_exit.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
extern "kernel32" fn ExitProcess(exit_code: c_uint) callconv(.winapi) noreturn;
test "foo" {
const value = bar() catch ExitProcess(1);
try expectEqual(1234, value);
}
fn bar() anyerror!u32 {
return 1234;
}
命令行
$ zig test test_noreturn_from_exit.zig -target x86_64-windows --test-no-exec