Zig 基本语法
本章将介绍 Zig 语言的基本语法规则,为后续学习打下坚实基础。
程序结构
最简单的 Zig 程序
zig
const std = @import("std");
pub fn main() void {
std.debug.print("Hello, World!\n", .{});
}让我们分析这个程序的每一部分:
const std = @import("std");- 导入标准库pub fn main() void- 定义公共的 main 函数,返回类型为 voidstd.debug.print()- 调用标准库的打印函数.{}- 空的参数元组
注释
单行注释
zig
// 这是单行注释
const x = 42; // 行末注释文档注释
zig
/// 这是文档注释,用于生成文档
/// 可以跨越多行
pub fn add(a: i32, b: i32) i32 {
return a + b;
}顶级文档注释
zig
//! 这是顶级文档注释
//! 用于描述整个文件或模块标识符
命名规则
- 以字母或下划线开头
- 可包含字母、数字、下划线
- 区分大小写
zig
const valid_name = 1;
const ValidName = 2;
const _private = 3;
const name123 = 4;命名约定
zig
// 变量和函数:snake_case
const my_variable = 42;
fn my_function() void {}
// 类型:PascalCase
const MyStruct = struct {};
const MyEnum = enum {};
// 常量:SCREAMING_SNAKE_CASE
const MAX_SIZE = 1024;关键字
Zig 的关键字不能用作标识符:
zig
// 控制流
if, else, switch, while, for, break, continue, return
// 类型相关
struct, enum, union, fn, var, const, comptime
// 错误处理
try, catch, error, defer, errdefer
// 其他
pub, export, extern, inline, noinline, packed, align
and, or, null, undefined, unreachable, async, await, suspend, resume语句和表达式
语句
语句执行操作但不返回值:
zig
const x = 42; // 声明语句
var y: i32 = 10; // 声明语句
y = 20; // 赋值语句表达式
表达式计算并返回值:
zig
const sum = 1 + 2; // 算术表达式
const is_equal = x == y; // 比较表达式
const result = if (x > 0) 1 else 0; // 条件表达式分号规则
Zig 中分号是可选的,但有特定规则:
zig
// 不需要分号的情况
const x = 42
const y = 24
// 需要分号的情况(同一行多个语句)
const a = 1; const b = 2;
// 函数调用后通常不需要分号
std.debug.print("Hello\n", .{})代码块
使用大括号 {} 定义代码块:
zig
pub fn main() void {
// 这是一个代码块
const x = 42;
if (x > 0) {
// 这是另一个代码块
std.debug.print("Positive\n", .{});
}
}运算符
算术运算符
zig
const a = 10;
const b = 3;
const sum = a + b; // 加法:13
const diff = a - b; // 减法:7
const product = a * b; // 乘法:30
const quotient = a / b; // 除法:3
const remainder = a % b; // 取模:1比较运算符
zig
const x = 10;
const y = 20;
const equal = x == y; // 等于:false
const not_equal = x != y; // 不等于:true
const less = x < y; // 小于:true
const less_equal = x <= y; // 小于等于:true
const greater = x > y; // 大于:false
const greater_equal = x >= y; // 大于等于:false逻辑运算符
zig
const a = true;
const b = false;
const and_result = a and b; // 逻辑与:false
const or_result = a or b; // 逻辑或:true
const not_result = !a; // 逻辑非:false位运算符
zig
const x: u8 = 0b1010; // 10
const y: u8 = 0b1100; // 12
const and_bits = x & y; // 按位与:0b1000 (8)
const or_bits = x | y; // 按位或:0b1110 (14)
const xor_bits = x ^ y; // 按位异或:0b0110 (6)
const not_bits = ~x; // 按位取反:0b11110101 (245)
const left_shift = x << 1; // 左移:0b10100 (20)
const right_shift = x >> 1; // 右移:0b0101 (5)字面量
整数字面量
zig
const decimal = 42; // 十进制
const binary = 0b101010; // 二进制
const octal = 0o52; // 八进制
const hex = 0x2A; // 十六进制
const with_underscores = 1_000_000; // 使用下划线分隔浮点字面量
zig
const float1 = 3.14; // 普通浮点数
const float2 = 1.23e-4; // 科学记数法
const float3 = 0x1.fp+1023; // 十六进制浮点数字符字面量
zig
const char = 'A'; // 字符字面量
const unicode = '中'; // Unicode 字符
const escape = '\n'; // 转义字符字符串字面量
zig
const string = "Hello, World!";
const multiline =
\\This is a
\\multiline string
\\using \\ prefix
;
const unicode_string = "你好,世界!";转义序列
zig
const newline = '\n'; // 换行
const tab = '\t'; // 制表符
const carriage_return = '\r'; // 回车
const backslash = '\\'; // 反斜杠
const quote = '\''; // 单引号
const double_quote = '\"'; // 双引号
const null_char = '\0'; // 空字符
const unicode = '\u{1F600}'; // Unicode 转义数组和切片字面量
zig
// 数组字面量
const array = [_]i32{1, 2, 3, 4, 5};
const explicit_array = [5]i32{1, 2, 3, 4, 5};
// 字符串切片
const slice: []const u8 = "Hello";结构体字面量
zig
const Point = struct {
x: f32,
y: f32,
};
const point = Point{
.x = 1.0,
.y = 2.0,
};
// 简化语法(字段名与变量名相同)
const x: f32 = 1.0;
const y: f32 = 2.0;
const point2 = Point{ x, y };函数调用语法
zig
// 基本函数调用
const result = add(1, 2);
// 方法调用语法
const string = "hello";
const length = string.len;
// 链式调用
const processed = data.filter().map().collect();错误处理语法
zig
// try 表达式
const file = try std.fs.cwd().openFile("data.txt", .{});
// catch 表达式
const value = parseNumber(input) catch 0;
// if 错误处理
if (parseNumber(input)) |num| {
// 成功情况
std.debug.print("Number: {}\n", .{num});
} else |err| {
// 错误情况
std.debug.print("Error: {}\n", .{err});
}可选类型语法
zig
var maybe_number: ?i32 = null;
maybe_number = 42;
// if 可选处理
if (maybe_number) |number| {
std.debug.print("Number: {}\n", .{number});
} else {
std.debug.print("No number\n", .{});
}
// orelse 操作符
const number = maybe_number orelse 0;编译时语法
zig
// comptime 关键字
comptime var compile_time_var = 42;
// 编译时函数调用
const result = comptime fibonacci(10);
// 编译时条件
const is_debug = comptime std.debug.runtime_safety;代码示例:综合语法演示
zig
const std = @import("std");
/// 计算两个数的和
pub fn add(a: i32, b: i32) i32 {
return a + b;
}
/// 主函数
pub fn main() void {
// 变量声明
const x = 10;
var y: i32 = 20;
// 算术运算
const sum = add(x, y);
const product = x * y;
// 条件表达式
const max = if (x > y) x else y;
// 字符串处理
const message = "计算结果";
// 输出结果
std.debug.print("{s}:\n", .{message});
std.debug.print("和: {}\n", .{sum});
std.debug.print("积: {}\n", .{product});
std.debug.print("最大值: {}\n", .{max});
// 循环
var i: i32 = 0;
while (i < 3) : (i += 1) {
std.debug.print("循环 {}\n", .{i});
}
}语法最佳实践
1. 保持一致的缩进
zig
// 好的做法
if (condition) {
doSomething();
doAnotherThing();
}
// 避免
if (condition) {
doSomething();
doAnotherThing();
}2. 合理使用空行
zig
const std = @import("std");
pub fn main() void {
const x = 42;
const y = 24;
const sum = x + y;
std.debug.print("Sum: {}\n", .{sum});
}3. 适当的注释
zig
// 解释复杂逻辑
const hash = computeHash(data); // 使用 FNV-1a 算法
/// 公共 API 需要文档注释
pub fn processData(input: []const u8) ![]u8 {
// 实现细节...
}总结
本章介绍了 Zig 的基本语法规则,包括:
- ✅ 程序结构和注释
- ✅ 标识符和关键字
- ✅ 运算符和字面量
- ✅ 基本语法结构
- ✅ 代码风格建议
掌握这些基础语法后,你就可以开始编写简单的 Zig 程序了。在下一章中,我们将学习 Zig 的变量声明。