第一个Zig程序 #
一、Hello World #
1.1 编写代码 #
创建文件 hello.zig:
zig
const std = @import("std");
pub fn main() void {
std.debug.print("Hello, World!\n", .{});
}
1.2 代码解析 #
让我们逐行分析这个程序:
zig
const std = @import("std");
@import("std"):导入 Zig 标准库const std:将标准库绑定到常量std
zig
pub fn main() void {
pub:公开函数,可被外部调用fn:函数关键字main:程序入口函数名():无参数void:无返回值
zig
std.debug.print("Hello, World!\n", .{});
std.debug.print:标准库的打印函数"Hello, World!\n":要打印的字符串.{}:格式化参数(空元组,表示无额外参数)
1.3 运行程序 #
直接运行:
bash
zig run hello.zig
输出:
text
Hello, World!
编译后运行:
bash
zig build-exe hello.zig
./hello
二、程序结构详解 #
2.1 导入语句 #
Zig 使用 @import 内置函数导入模块:
zig
const std = @import("std");
const http = @import("std").http;
const math = @import("std").math;
2.2 main 函数 #
main 函数是程序的入口点,有两种形式:
无返回值:
zig
pub fn main() void {
// 程序代码
}
返回错误:
zig
pub fn main() !void {
// 可能失败的代码
try someFunction();
}
使用分配器:
zig
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// 使用 allocator
}
2.3 注释 #
Zig 支持三种注释:
zig
// 单行注释
/// 文档注释(用于函数、类型等)
//! 顶层文档注释(用于文件级别)
示例:
zig
/// 计算两个数的和
fn add(a: i32, b: i32) i32 {
return a + b;
}
//! 这是一个示例模块
//! 用于演示 Zig 的基本语法
三、格式化输出 #
3.1 基本格式化 #
zig
const std = @import("std");
pub fn main() void {
const name = "Zig";
const version = 0.13;
const year = 2024;
std.debug.print("Language: {s}\n", .{name});
std.debug.print("Version: {d}\n", .{version});
std.debug.print("Year: {}\n", .{year});
}
3.2 格式化占位符 #
| 占位符 | 说明 | 示例 |
|---|---|---|
{} |
默认格式 | print("{}", .{42}) |
{d} |
十进制整数 | print("{d}", .{42}) |
{x} |
十六进制 | print("{x}", .{255}) |
{s} |
字符串 | print("{s}", .{"hello"}) |
{c} |
字符 | print("{c}", .{'A'}) |
{e} |
科学计数法 | print("{e}", .{3.14}) |
{b} |
二进制 | print("{b}", .{10}) |
{o} |
八进制 | print("{o}", .{8}) |
3.3 宽度和精度 #
zig
const std = @import("std");
pub fn main() void {
const pi = 3.14159265;
// 宽度
std.debug.print("{d:10}\n", .{42});
// 精度
std.debug.print("{d:.2}\n", .{pi});
// 宽度和精度
std.debug.print("{d:10.2}\n", .{pi});
}
3.4 位置参数 #
zig
const std = @import("std");
pub fn main() void {
std.debug.print("{0} + {1} = {2}\n", .{ 1, 2, 3 });
std.debug.print("{1} - {0} = {2}\n", .{ 1, 2, 1 });
}
四、命令行参数 #
4.1 获取参数 #
zig
const std = @import("std");
pub fn main() void {
const args = std.process.argsAlloc(std.heap.page_allocator) catch return;
defer std.process.argsFree(std.heap.page_allocator, args);
std.debug.print("Program: {s}\n", .{args[0]});
for (args[1..], 0..) |arg, i| {
std.debug.print("Arg {}: {s}\n", .{ i, arg });
}
}
4.2 环境变量 #
zig
const std = @import("std");
pub fn main() !void {
const home = std.process.getEnvVarOwned(std.heap.page_allocator, "HOME") catch |err| {
std.debug.print("Error: {}\n", .{err});
return;
};
defer std.heap.page_allocator.free(home);
std.debug.print("HOME: {s}\n", .{home});
}
五、编译选项 #
5.1 优化级别 #
bash
# 调试模式(默认)
zig build-exe hello.zig
# 发布优化
zig build-exe hello.zig -O ReleaseFast
zig build-exe hello.zig -O ReleaseSafe
zig build-exe hello.zig -O ReleaseSmall
| 模式 | 说明 |
|---|---|
| Debug | 默认,包含调试信息 |
| ReleaseFast | 最大优化,不检查安全 |
| ReleaseSafe | 优化并保留安全检查 |
| ReleaseSmall | 优化二进制大小 |
5.2 指定输出 #
bash
zig build-exe hello.zig -o myapp
5.3 链接系统库 #
bash
zig build-exe hello.zig -lc
六、多文件项目 #
6.1 项目结构 #
text
myapp/
├── build.zig
└── src/
├── main.zig
└── utils.zig
6.2 utils.zig #
zig
pub fn greet(name: []const u8) void {
std.debug.print("Hello, {s}!\n", .{name});
}
const std = @import("std");
6.3 main.zig #
zig
const std = @import("std");
const utils = @import("utils.zig");
pub fn main() void {
utils.greet("Zig");
}
6.4 编译运行 #
bash
cd src
zig run main.zig
七、使用构建系统 #
7.1 初始化项目 #
bash
mkdir myapp
cd myapp
zig init
生成的文件结构:
text
myapp/
├── build.zig # 构建脚本
├── build.zig.zon # 项目配置
└── src/
└── main.zig # 主程序
7.2 build.zig #
zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "myapp",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the application");
run_step.dependOn(&run_cmd.step);
}
7.3 构建命令 #
bash
# 构建
zig build
# 运行
zig build run
# 安装
zig build install
# 清理
zig build clean
八、错误处理入门 #
8.1 错误联合类型 #
zig
const std = @import("std");
fn divide(a: i32, b: i32) !i32 {
if (b == 0) {
return error.DivisionByZero;
}
return @divTrunc(a, b);
}
pub fn main() void {
const result = divide(10, 2) catch |err| {
std.debug.print("Error: {}\n", .{err});
return;
};
std.debug.print("Result: {}\n", .{result});
}
8.2 try 关键字 #
zig
const std = @import("std");
fn readFile(path: []const u8) ![]u8 {
_ = path;
return error.NotImplemented;
}
pub fn main() !void {
const content = try readFile("test.txt");
defer std.heap.page_allocator.free(content);
std.debug.print("{s}\n", .{content});
}
九、实战练习 #
9.1 练习1:打印个人信息 #
创建一个程序,打印你的姓名、年龄和爱好:
zig
const std = @import("std");
pub fn main() void {
const name = "张三";
const age = 25;
const hobbies = [_][]const u8{ "编程", "阅读", "运动" };
std.debug.print("姓名: {s}\n", .{name});
std.debug.print("年龄: {}\n", .{age});
std.debug.print("爱好: ", .{});
for (hobbies) |hobby| {
std.debug.print("{s} ", .{hobby});
}
std.debug.print("\n", .{});
}
9.2 练习2:计算器 #
创建一个简单的计算器:
zig
const std = @import("std");
fn add(a: i32, b: i32) i32 {
return a + b;
}
fn subtract(a: i32, b: i32) i32 {
return a - b;
}
fn multiply(a: i32, b: i32) i32 {
return a * b;
}
fn divide(a: i32, b: i32) !i32 {
if (b == 0) return error.DivisionByZero;
return @divTrunc(a, b);
}
pub fn main() void {
const a: i32 = 10;
const b: i32 = 3;
std.debug.print("{} + {} = {}\n", .{ a, b, add(a, b) });
std.debug.print("{} - {} = {}\n", .{ a, b, subtract(a, b) });
std.debug.print("{} * {} = {}\n", .{ a, b, multiply(a, b) });
const result = divide(a, b) catch |err| {
std.debug.print("除法错误: {}\n", .{err});
return;
};
std.debug.print("{} / {} = {}\n", .{ a, b, result });
}
十、总结 #
第一个 Zig 程序的关键点:
| 概念 | 说明 |
|---|---|
| @import | 导入模块 |
| main函数 | 程序入口 |
| std.debug.print | 格式化输出 |
| zig run | 直接运行 |
| zig build-exe | 编译可执行文件 |
下一步,让我们深入学习 Zig 的基础语法!
最后更新:2026-03-27