Zig 是一种专注于安全性、性能和可维护性的系统编程语言。本快速入门文档介绍 Zig 的基本概念和用法,帮助你在 30 分钟内掌握核心知识。
Table of contents
Open Table of contents
1. 安装 Zig
从 ziglang.org 下载并安装 Zig。
zig version # 验证安装是否成功
2. Hello, World
const std = @import("std");
pub fn main() void {
std.debug.print("Hello, Zig!\n", .{});
}
编译并运行:
zig run hello.zig
3. 变量与常量
const a: i32 = 10; // 常量
var b: i32 = 20; // 变量
b = 30;
const
定义常量var
定义变量- 变量默认不可变,需
var
声明可变性
4. 基本数据类型
const intVal: i32 = 42;
const floatVal: f64 = 3.14;
const boolVal: bool = true;
const charVal: u8 = 'A';
- Zig 支持
i8, i16, i32, i64, u8, u16, u32, u64
整数类型 f16, f32, f64
浮点数bool
布尔类型u8
代表 ASCII 字符
5. 控制流
5.1 if-else
if (a > 0) {
std.debug.print("Positive\n", .{});
} else {
std.debug.print("Negative\n", .{});
}
5.2 while 循环
var i: i32 = 0;
while (i < 5) : (i += 1) {
std.debug.print("{} ", .{i});
}
5.3 for 循环
const arr = [_]i32{ 1, 2, 3 };
for (arr) |val| {
std.debug.print("{} ", .{val});
}
6. 函数
fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn main() void {
const result = add(5, 10);
std.debug.print("Sum: {}\n", .{result});
}
- 使用
fn
定义函数 - 返回值类型在参数列表后声明
pub
关键字使函数可在模块外部访问
7. 结构体和枚举
7.1 结构体
const Person = struct {
name: []const u8,
age: u8,
};
const alice = Person{ .name = "Alice", .age = 30 };
7.2 枚举
enum Color {
Red,
Green,
Blue,
}
const myColor = Color.Green;
8. 指针与数组
8.1 指针
const x: i32 = 10;
const ptr: *const i32 = &x;
std.debug.print("{}\n", .{ptr.*});
8.2 数组
const arr = [_]i32{ 1, 2, 3 };
const slice: []const i32 = &arr;
std.debug.print("First: {}\n", .{slice[0]});
9. 错误处理
fn mayFail(x: i32) !i32 {
if (x < 0) return error.NegativeValue;
return x;
}
pub fn main() void {
const result = mayFail(-1) catch {
std.debug.print("Error occurred!\n", .{});
return;
};
std.debug.print("Success: {}\n", .{result});
}
!
表示函数可能返回错误- 使用
catch
处理错误
10. 线程与并发
const std = @import("std");
fn worker() void {
std.debug.print("Worker thread running\n", .{});
}
pub fn main() void {
var thread = try std.Thread.spawn(.{}, worker, .{});
thread.join();
}
- 使用
std.Thread.spawn()
创建线程 thread.join()
等待线程结束
11. 编译和优化
11.1 直接运行
zig run main.zig
11.2 生成可执行文件
zig build-exe main.zig
11.3 交叉编译
zig build-exe -target x86_64-windows main.zig
12. 资源
- 官方网站: https://ziglang.org
- 官方文档: https://ziglang.org/documentation/master/
- GitHub: https://github.com/ziglang/zig
总结
本指南介绍了 Zig 语言的核心特性,包括变量、控制流、函数、结构体、错误处理等。希望对你有所帮助!