值
// 顶层声明与顺序无关:
const print = std.debug.print;
const std = @import("std");
const os = std.os;
const assert = std.debug.assert;
// 自定义错误集合定义:
const ExampleErrorSet = error{
ExampleErrorVariant,
};
pub fn main() void {
// 整数
const one_plus_one: i32 = 1 + 1;
print("1 + 1 = {}\n", .{one_plus_one});
// 浮点数
const seven_div_three: f32 = 7.0 / 3.0;
print("7.0 / 3.0 = {}\n", .{seven_div_three});
// 布尔值
print("{}\n{}\n{}\n", .{
true and false,
true or false,
!true,
});
// 可选值
var optional_value: ?[]const u8 = null;
assert(optional_value == null);
print("\noptional 1\ntype: {}\nvalue: {?s}\n", .{
@TypeOf(optional_value), optional_value,
});
optional_value = "hi";
assert(optional_value != null);
print("\noptional 2\ntype: {}\nvalue: {?s}\n", .{
@TypeOf(optional_value), optional_value,
});
// 错误联合
var number_or_error: ExampleErrorSet!i32 = ExampleErrorSet.ExampleErrorVariant;
print("\nerror union 1\ntype: {}\nvalue: {!}\n", .{
@TypeOf(number_or_error),
number_or_error,
});
number_or_error = 1234;
print("\nerror union 2\ntype: {}\nvalue: {!}\n", .{
@TypeOf(number_or_error), number_or_error,
});
}$ zig build-exe values.zig
$ ./values
1 + 1 = 2
7.0 / 3.0 = 2.3333333
false
true
false
optional 1
type: ?[]const u8
value: null
optional 2
type: ?[]const u8
value: hi
error union 1
type: error{ExampleErrorVariant}!i32
value: error.ExampleErrorVariant
error union 2
type: error{ExampleErrorVariant}!i32
value: 1234
基本类型
| 类型 | C 对应类型 | 说明 |
|---|---|---|
i8 |
int8_t |
8 位有符号整数 |
u8 |
uint8_t |
8 位无符号整数 |
i16 |
int16_t |
16 位有符号整数 |
u16 |
uint16_t |
16 位无符号整数 |
i32 |
int32_t |
32 位有符号整数 |
u32 |
uint32_t |
32 位无符号整数 |
i64 |
int64_t |
64 位有符号整数 |
u64 |
uint64_t |
64 位无符号整数 |
i128 |
__int128 |
128 位有符号整数 |
u128 |
unsigned __int128 |
128 位无符号整数 |
isize |
intptr_t, ssize_t |
与指针等宽的有符号整数 |
usize |
uintptr_t, size_t |
与指针等宽的无符号整数。另见 #5185 |
c_char |
char |
用于兼容 C ABI |
c_short |
short |
用于兼容 C ABI |
c_ushort |
unsigned short |
用于兼容 C ABI |
c_int |
int |
用于兼容 C ABI |
c_uint |
unsigned int |
用于兼容 C ABI |
c_long |
long |
用于兼容 C ABI |
c_ulong |
unsigned long |
用于兼容 C ABI |
c_longlong |
long long |
用于兼容 C ABI |
c_ulonglong |
unsigned long long |
用于兼容 C ABI |
c_longdouble |
long double |
用于兼容 C ABI |
f16 |
_Float16 |
16 位浮点数(10 位尾数),IEEE-754-2008 binary16 |
f32 |
float |
32 位浮点数(23 位尾数),IEEE-754-2008 binary32 |
f64 |
double |
64 位浮点数(52 位尾数),IEEE-754-2008 binary64 |
f80 |
long double |
80 位浮点数(64 位尾数),IEEE-754-2008 80 位扩展精度 |
f128 |
_Float128 |
128 位浮点数(112 位尾数),IEEE-754-2008 binary128 |
bool |
bool |
true 或 false |
anyopaque |
void |
用于类型擦除的指针。 |
noreturn |
(无) | break、continue、return、unreachable 和 while (true) {} 的类型 |
type |
(无) | 类型本身的类型 |
anyerror |
(无) | 错误码 |
comptime_int |
(无) | 仅允许用于编译时已知的值。整数字面量的类型。 |
comptime_float |
(无) | 仅允许用于编译时已知的值。浮点数字面量的类型。 |
除上述整数类型外,还可以使用字母 i 或 u 后接数字的标识符引用任意位宽整数。例如,标识符 i7 表示 7 位有符号整数。整数类型允许的最大位宽为 65535。
另见:
基本值
| 名称 | 说明 |
|---|---|
true 和 false |
bool 类型的值 |
null |
用于将可选类型的值设为 null |
undefined |
用于让值保持未指定状态 |
另见:
字符串字面量与 Unicode 码点字面量
字符串字面量是指向以 null 结尾的字节数组的常量单项指针。字符串字面量的类型同时记录了长度和以 null 结尾这一事实,因此既能强制转换为切片,也能转换为以 null 结尾的指针。对字符串字面量解引用会得到数组。
由于 Zig 源码采用 UTF-8 编码,源码中字符串字面量内出现的非 ASCII 字节会以原本的 UTF-8 含义进入 Zig 程序的字符串内容;编译器不会修改这些字节。使用 \xNN 写法还可以在字符串字面量中嵌入非 UTF-8 字节。
对包含非 ASCII 字节的字符串取索引,得到的是单个字节,无论它是否构成有效 UTF-8。
Unicode 码点字面量的类型是 comptime_int,与整数字面量相同。所有转义序列都既适用于字符串字面量,也适用于 Unicode 码点字面量。
const print = @import("std").debug.print;
const mem = @import("std").mem; // 将用于比较字节
pub fn main() void {
const bytes = "hello";
print("{}\n", .{@TypeOf(bytes)}); // *const [5:0]u8
print("{d}\n", .{bytes.len}); // 5
print("{c}\n", .{bytes[1]}); // 'e'
print("{d}\n", .{bytes[5]}); // 0
print("{}\n", .{'e' == '\x65'}); // true
print("{d}\n", .{'\u{1f4a9}'}); // 128169
print("{d}\n", .{'💯'}); // 128175
print("{u}\n", .{'⚡'});
print("{}\n", .{mem.eql(u8, "hello", "h\x65llo")}); // true
print("{}\n", .{mem.eql(u8, "💯", "\xf0\x9f\x92\xaf")}); // 同样为 true
const invalid_utf8 = "\xff\xfe"; // 使用 \xNN 写法可以表示非 UTF-8 字符串。
print("0x{x}\n", .{invalid_utf8[1]}); // 对它们索引返回单个字节……
print("0x{x}\n", .{"💯"[1]}); // ……即使索引位于非 ASCII 字符的中间也是如此
}$ zig build-exe string_literals.zig
$ ./string_literals
*const [5:0]u8
5
e
0
true
128169
128175
⚡
true
true
0xfe
0x9f
另见:
转义序列
| 转义序列 | 名称 |
|---|---|
\n |
换行 |
\r |
回车 |
\t |
制表符 |
\\ |
反斜杠 |
\' |
单引号 |
\" |
双引号 |
\xNN |
十六进制的 8 位字节值(2 位数字) |
\u{NNNNNN} |
十六进制 Unicode 标量值,以 UTF-8 编码(1 位或更多数字) |
注意,有效 Unicode 标量值的最大值为 0x10ffff。
多行字符串字面量
多行字符串字面量不处理转义,并且可以跨越多行。使用 \\ 标记开始一个多行字符串字面量。与注释类似,该字符串字面量持续到行尾;行尾本身不计入字符串。但是,如果下一行以 \\ 开头,就会追加一个换行符,并继续该字符串字面量。
const hello_world_in_c =
\\#include <stdio.h>
\\
\\int main(int argc, char **argv) {
\\ printf("hello world\n");
\\ return 0;
\\}
;另见:
赋值
使用 const 关键字为标识符赋值:
const x = 1234;
fn foo() void {
// 在文件作用域和函数内部都可以使用。
const y = 5678;
// 赋值之后,标识符不可再修改。
y += 1;
}
pub fn main() void {
foo();
}$ zig build-exe constant_identifier_cannot_change.zig
/home/alexrp/Sources/ziglang/zig/doc/langref/constant_identifier_cannot_change.zig:8:5: error: cannot assign to constant
y += 1;
^
referenced by:
main: /home/alexrp/Sources/ziglang/zig/doc/langref/constant_identifier_cannot_change.zig:12:8
callMain [inlined]: /home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/start.zig:788:64
callMainWithArgs [inlined]: /home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/start.zig:729:20
posixCallMainAndExit: /home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/start.zig:681:38
2 reference(s) hidden; use '-freference-trace=6' to see all references
const 适用于标识符直接寻址的全部字节。指针具有独立的常量性。
需要可修改的变量时,使用 var 关键字:
const print = @import("std").debug.print;
pub fn main() void {
var y: i32 = 5678;
y += 1;
print("{d}", .{y});
}$ zig build-exe mutable_var.zig
$ ./mutable_var
5679
变量必须初始化:
pub fn main() void {
var x: i32;
x = 1;
}$ zig build-exe var_must_be_initialized.zig
/home/alexrp/Sources/ziglang/zig/doc/langref/var_must_be_initialized.zig:2:15: error: expected '=', found ';'
var x: i32;
^
undefined
使用 undefined 可以让变量保持未初始化状态:
const print = @import("std").debug.print;
pub fn main() void {
var x: i32 = undefined;
x = 1;
print("{d}", .{x});
}$ zig build-exe assign_undefined.zig
$ ./assign_undefined
1
undefined 可以强制转换为任意类型。一旦转换,就无法再检测出该值原先是 undefined。undefined 表示该值可能是任何内容,甚至可能是不符合其类型含义的内容。用自然语言解释,undefined 的意思是“这不是有意义的值。使用它就是程序错误。该值将不会使用,或者在使用前会被覆盖”。
在 debug 和 safe 模式下,Zig 会向未定义内存写入 0xaa 字节,以便尽早发现程序错误,并帮助调试器检测未定义内存的使用。但这仅是实现细节,不是语言语义,因此不保证代码可以观察到这种行为。
解构
解构赋值可以拆分可索引聚合类型中的元素,包括元组、数组和向量:
const print = @import("std").debug.print;
pub fn main() void {
var x: u32 = undefined;
var y: u32 = undefined;
var z: u32 = undefined;
const tuple = .{ 1, 2, 3 };
x, y, z = tuple;
print("tuple: x = {}, y = {}, z = {}\n", .{x, y, z});
const array = [_]u32{ 4, 5, 6 };
x, y, z = array;
print("array: x = {}, y = {}, z = {}\n", .{x, y, z});
const vector: @Vector(3, u32) = .{ 7, 8, 9 };
x, y, z = vector;
print("vector: x = {}, y = {}, z = {}\n", .{x, y, z});
}$ zig build-exe destructuring_to_existing.zig
$ ./destructuring_to_existing
tuple: x = 1, y = 2, z = 3
array: x = 4, y = 5, z = 6
vector: x = 7, y = 8, z = 9
解构表达式只能出现在块内,即不能位于命名空间作用域。赋值左侧必须是逗号分隔的列表,其中每一项可以是左值(例如现有的 var)或变量声明:
const print = @import("std").debug.print;
pub fn main() void {
var x: u32 = undefined;
const tuple = .{ 1, 2, 3 };
x, var y : u32, const z = tuple;
print("x = {}, y = {}, z = {}\n", .{x, y, z});
// y 可变
y = 100;
// 可以使用 _ 丢弃不需要的值。
_, x, _ = tuple;
print("x = {}\n", .{x});
}$ zig build-exe destructuring_mixed.zig
$ ./destructuring_mixed
x = 1, y = 2, z = 3
x = 2
解构前面可以添加 comptime 关键字,此时整个解构表达式在编译时求值。所有声明的 var 都成为 comptime var,所有表达式(包括结果位置和被赋值表达式)均在编译时求值。
另见: