Skip to content

Zig quickstart in 30 mins(30 分钟快速入门Zig)

Published: at 12:00 AMSuggest Changes

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;

4. 基本数据类型

const intVal: i32 = 42;
const floatVal: f64 = 3.14;
const boolVal: bool = true;
const charVal: u8 = 'A';

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});
}

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});
}

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();
}

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. 资源


总结

本指南介绍了 Zig 语言的核心特性,包括变量、控制流、函数、结构体、错误处理等。希望对你有所帮助!


Previous Post
Introduction to Zig - a project-based book(电子书推荐)