Zig基础语法 #

一、注释 #

1.1 单行注释 #

使用 // 开始,到行尾结束:

zig
// 这是一个单行注释
const x = 10; // 行尾注释

1.2 文档注释 #

使用 /// 开始,用于文档生成:

zig
/// 计算两个整数的和
/// 
/// 参数:
///   a - 第一个整数
///   b - 第二个整数
/// 
/// 返回:
///   两数之和
fn add(a: i32, b: i32) i32 {
    return a + b;
}

1.3 顶层文档注释 #

使用 //! 开始,用于文件级别的文档:

zig
//! 数学工具库
//! 
//! 这个模块提供常用的数学函数
//! 
//! 示例:
//! ```zig
//! const math = @import("math.zig");
//! const sum = math.add(1, 2);
//! ```

pub fn add(a: i32, b: i32) i32 {
    return a + b;
}

1.4 注释最佳实践 #

zig
// 好的注释:解释为什么
// 使用位运算代替乘法,因为性能更好
const result = value << 1;

// 不好的注释:重复代码内容
// 将 value 左移一位
const result = value << 1;

二、标识符 #

2.1 命名规则 #

标识符必须以字母或下划线开头,后面可以跟字母、数字或下划线:

zig
// 合法标识符
const name = "Zig";
const _private = 10;
const value1 = 100;
const my_variable = "hello";
const MyType = struct {};

// 非法标识符
// const 1value = 10;    // 错误:以数字开头
// const my-var = 20;    // 错误:包含连字符
// const class = 30;     // 错误:可能是关键字

2.2 命名约定 #

类型 命名风格 示例
变量 snake_case user_name, item_count
常量 snake_case max_size, default_port
函数 snake_case get_value(), calculate_sum()
类型 PascalCase User, Config, ArrayList
错误 snake_case file_not_found, invalid_input
枚举值 snake_case .red, .blue, .green

2.3 示例 #

zig
const std = @import("std");

// 类型:PascalCase
const Person = struct {
    name: []const u8,
    age: u32,
};

// 常量:snake_case
const max_connections = 100;
const default_timeout = 30;

// 函数:snake_case
fn calculate_area(width: f32, height: f32) f32 {
    return width * height;
}

// 错误集
const FileError = error{
    not_found,
    permission_denied,
    invalid_format,
};

pub fn main() void {
    // 变量:snake_case
    const user_name = "Alice";
    var item_count: u32 = 0;
    
    std.debug.print("User: {s}\n", .{user_name});
}

2.4 匿名标识符 #

使用 _ 表示忽略的值:

zig
const std = @import("std");

pub fn main() void {
    // 忽略返回值
    _ = std.debug.print("Hello\n", .{});
    
    // 忽略元组中的某些值
    const tuple = .{ 1, 2, 3 };
    const first, _, _ = tuple;
    
    // 忽略循环索引
    const items = [_]i32{ 1, 2, 3 };
    for (items) |_| {
        std.debug.print("Item\n", .{});
    }
}

三、关键字 #

3.1 完整关键字列表 #

Zig 共有关键字(保留字):

关键字 用途
addrspace 地址空间
align 内存对齐
allowzero 允许零指针
and 逻辑与
anyframe 异步帧类型
anytype 任意类型
asm 内联汇编
async 异步函数
await 等待异步结果
break 跳出循环
callconv 调用约定
catch 错误捕获
comptime 编译时执行
const 常量声明
continue 继续下一次循环
defer 延迟执行
else 否则分支
enum 枚举类型
errdefer 错误时延迟执行
error 错误类型
export 导出符号
extern 外部链接
fn 函数声明
for 循环
if 条件判断
inline 内联
noalias 无别名指针
noinline 禁止内联
nosuspend 非挂起块
opaque 不透明类型
or 逻辑或
orelse 可选值默认
packed 紧凑结构
pub 公开可见性
resume 恢复异步帧
return 函数返回
linksection 链接段
struct 结构体
suspend 挂起异步帧
switch 多路分支
test 测试块
threadlocal 线程局部存储
try 错误传播
union 联合体
unreachable 不可达代码
usingnamespace 引入命名空间
var 变量声明
volatile 易变访问
while 循环

3.2 关键字使用示例 #

zig
const std = @import("std");

// const 和 var
const constant_value: i32 = 100;
var mutable_value: i32 = 0;

// fn 和 pub
pub fn public_function() void {}
fn private_function() void {}

// struct
const Point = struct {
    x: f32,
    y: f32,
};

// enum
const Color = enum {
    red,
    green,
    blue,
};

// union
const Value = union {
    int: i32,
    float: f32,
    string: []const u8,
};

// error
const MyError = error{
    invalid_input,
    out_of_range,
};

// if 和 else
fn check_value(x: i32) void {
    if (x > 0) {
        std.debug.print("Positive\n", .{});
    } else if (x < 0) {
        std.debug.print("Negative\n", .{});
    } else {
        std.debug.print("Zero\n", .{});
    }
}

// for 和 while
fn loops() void {
    // for 循环
    const items = [_]i32{ 1, 2, 3 };
    for (items) |item| {
        std.debug.print("{}\n", .{item});
    }

    // while 循环
    var i: usize = 0;
    while (i < 3) : (i += 1) {
        std.debug.print("{}\n", .{i});
    }
}

// switch
fn describe_color(c: Color) []const u8 {
    return switch (c) {
        .red => "Red color",
        .green => "Green color",
        .blue => "Blue color",
    };
}

// defer
fn with_defer() void {
    std.debug.print("Start\n", .{});
    defer std.debug.print("End\n", .{});
    std.debug.print("Middle\n", .{});
}

// comptime
fn fibonacci(comptime n: u32) u32 {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

// try 和 catch
fn might_fail() !void {
    return error.something_went_wrong;
}

fn handle_error() void {
    might_fail() catch |err| {
        std.debug.print("Error: {}\n", .{err});
    };
}

// test
test "basic test" {
    try std.testing.expect(1 + 1 == 2);
}

四、运算符 #

4.1 算术运算符 #

zig
const a: i32 = 10;
const b: i32 = 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

4.2 比较运算符 #

zig
const a: i32 = 10;
const b: i32 = 20;

const eq = a == b;    // 等于: false
const ne = a != b;    // 不等于: true
const lt = a < b;     // 小于: true
const le = a <= b;    // 小于等于: true
const gt = a > b;     // 大于: false
const ge = a >= b;    // 大于等于: false

4.3 逻辑运算符 #

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

4.4 位运算符 #

zig
const a: u8 = 0b1010;
const b: u8 = 0b1100;

const band = a & b;    // 按位与: 0b1000
const bor = a | b;     // 按位或: 0b1110
const bxor = a ^ b;    // 按位异或: 0b0110
const bnot = ~a;       // 按位取反: 0b0101
const left = a << 2;   // 左移: 0b101000
const right = a >> 2;  // 右移: 0b0010

4.5 赋值运算符 #

zig
var x: i32 = 10;

x += 5;   // x = x + 5
x -= 3;   // x = x - 3
x *= 2;   // x = x * 2
x /= 4;   // x = x / 4
x %= 3;   // x = x % 3
x &= 0xFF;  // x = x & 0xFF
x |= 0x0F;  // x = x | 0x0F
x ^= 0x55;  // x = x ^ 0x55
x <<= 1;    // x = x << 1
x >>= 1;    // x = x >> 1

4.6 指针运算符 #

zig
var value: i32 = 10;
const ptr: *i32 = &value;  // 取地址
const deref = ptr.*;       // 解引用

4.7 可选类型运算符 #

zig
const maybe: ?i32 = 42;

const value = maybe orelse 0;  // 默认值
const unwrapped = maybe.?;     // 解包(可能panic)

4.8 错误处理运算符 #

zig
const result: anyerror!i32 = 42;

const value = result catch 0;  // 错误默认值
const unwrapped = try result;  // 错误传播

五、表达式与语句 #

5.1 表达式 #

Zig 中几乎所有东西都是表达式:

zig
const std = @import("std");

pub fn main() void {
    // if 是表达式
    const x = 10;
    const result = if (x > 5) "big" else "small";
    std.debug.print("{s}\n", .{result});

    // switch 是表达式
    const color = .red;
    const description = switch (color) {
        .red => "Red",
        .green => "Green",
        .blue => "Blue",
    };

    // 块是表达式
    const value = blk: {
        var sum: i32 = 0;
        var i: i32 = 1;
        while (i <= 10) : (i += 1) {
            sum += i;
        }
        break :blk sum;
    };
    std.debug.print("Sum: {}\n", .{value});
}

5.2 语句 #

语句以分号结尾:

zig
const x = 10;           // 声明语句
std.debug.print("Hi", .{});  // 表达式语句
return;                 // 返回语句

六、代码块与作用域 #

6.1 代码块 #

zig
const std = @import("std");

pub fn main() void {
    // 块表达式
    const result = blk: {
        const a = 10;
        const b = 20;
        break :blk a + b;
    };
    std.debug.print("Result: {}\n", .{result});
}

6.2 变量遮蔽 #

Zig 允许变量遮蔽,但会产生警告:

zig
const std = @import("std");

pub fn main() void {
    const x = 10;
    const x = 20;  // 遮蔽外层 x
    std.debug.print("x = {}\n", .{x});  // 输出 20
}

七、代码规范 #

7.1 缩进 #

使用 4 个空格缩进:

zig
const std = @import("std");

pub fn main() void {
    if (true) {
        std.debug.print("Hello\n", .{});
    }
}

7.2 行宽 #

建议每行不超过 100 个字符。

7.3 空行 #

zig
const std = @import("std");

const Person = struct {
    name: []const u8,
    age: u32,
};

pub fn main() void {
    const person = Person{
        .name = "Alice",
        .age = 30,
    };
    
    std.debug.print("Name: {s}\n", .{person.name});
}

7.4 代码格式化 #

使用 zig fmt 自动格式化代码:

bash
zig fmt main.zig
zig fmt src/

八、总结 #

Zig 基础语法要点:

概念 说明
注释 ///////!
标识符 snake_case 变量,PascalCase 类型
关键字 保留字,不可用作标识符
运算符 算术、比较、逻辑、位运算等
表达式 几乎所有东西都是表达式
格式化 使用 zig fmt

下一步,让我们学习 Zig 的数据类型!

最后更新:2026-03-27