Zig 是一种现代、低级、高效的系统编程语言,设计目标是安全性、可读性和可预测的性能。它旨在成为 C 的替代品,同时提供更好的工具支持、更强的类型安全性,并去除 C 的历史遗留问题。
目录
1. 基本概念
Zig 语言特点
- 无隐藏控制流:避免了 C++ 的 RAII(资源获取即初始化)和异常处理等隐式行为。
- 无垃圾回收(GC):程序员手动管理内存,提高性能和可预测性。
- 直接与 C 交互:可无缝调用 C 代码和库。
- 强类型检查:可避免 C 语言中常见的未定义行为(UB)。
- 编译时计算:使用
comptime
关键字实现强大的编译时优化。
Hello World
const std = @import("std");
pub fn main() void {
std.debug.print("Hello, Zig!\n", .{});
}
2. 数据类型与变量
基本数据类型
const a: i32 = 42; // 32位有符号整数
const b: u64 = 100; // 64位无符号整数
const pi: f64 = 3.14159; // 64位浮点数
const flag: bool = true; // 布尔值
const letter: u8 = 'A'; // 字符
变量与常量
var x: i32 = 10; // 变量
x = 20;
const y: i32 = 30; // 常量
// y = 40; // 错误!常量不可变
3. 控制流
条件语句
if (x > 10) {
std.debug.print("x is greater than 10\n", .{});
} else {
std.debug.print("x is 10 or less\n", .{});
}
循环
while
var i: i32 = 0;
while (i < 5) : (i += 1) {
std.debug.print("i: {}\n", .{i});
}
for
const arr = [_]i32{1, 2, 3, 4, 5};
for (arr) |item| {
std.debug.print("Item: {}\n", .{item});
}
4. 函数
定义函数
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});
}
5. 数组与指针
数组
const arr = [_]i32{1, 2, 3, 4, 5};
指针
const a: i32 = 42;
const ptr: *const i32 = &a;
6. 结构体与联合体
结构体
const Person = struct {
name: []const u8,
age: u8,
};
const john = Person{ .name = "John", .age = 25 };
联合体
const Value = union(enum) {
int: i32,
float: f32,
};
const v = Value{ .int = 42 };
7. 错误处理
fn divide(a: i32, b: i32) !i32 {
if (b == 0) return error.DivisionByZero;
return a / b;
}
pub fn main() void {
const result = divide(10, 0) catch |err| {
std.debug.print("Error: {}\n", .{err});
return;
};
std.debug.print("Result: {}\n", .{result});
}
8. 内存管理
const allocator = std.heap.page_allocator;
const buffer = try allocator.alloc(u8, 100);
defer allocator.free(buffer);
9. 并发
const std = @import("std");
pub fn main() void {
var thread = try std.Thread.spawn(.{}, worker, .{});
thread.join();
}
fn worker() void {
std.debug.print("Running in a thread!\n", .{});
}
10. Zig 交互 C 代码
extern fn printf(format: [*:0]const u8, ...) c_int;
pub fn main() void {
_ = printf("Hello from Zig!\n");
}
11. Zig 编译与运行
zig build-exe main.zig
./main
12. 参考资料
Zig 是一门高效、安全的系统编程语言,适用于嵌入式开发、游戏开发和高性能计算! 🚀
发表回复