目前我們已經安裝好 Zig 了,總算是可以來實際寫寫 Zig 並試著運行了。
建立專案
首先建立一個資料夾 zig-hello:
mkdir zig-hellocd zig-hello初始化 Zig 專案:
zig init完成後你應該會看到類似這樣的檔案結構:
zig-hello ├── src │ ├── main.zig │ └── root.zig ├── build.zig └── build.zig.zonbuild.zig.zon是一個類似 JSON 格式的檔案,它就類似package.json,會包含此專案的名稱、版本、依賴套件等資訊。build.zig是類似 Makefile 或 CMakeLists 的檔案,用來配置建構系統如何進行編譯和連結。main.zig就是主要執行程式。root.zig在這裡是一個範例函式庫。
生成的專案沒有 .gitignore,你可以用這個:
# Source: https://github.com/ziglang/zig/blob/master/.gitignore# andrewrk
.zig-cache/zig-cache/zig-out//release//debug//build//build-*//docgen_tmp/執行
目前的 main.zig 應該是這樣的(省略部分註解):
const std = @import("std");
pub fn main() !void { // Prints to stderr (it's a shortcut based on `std.io.getStdErr()`) std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
const stdout_file = std.io.getStdOut().writer(); var bw = std.io.bufferedWriter(stdout_file); const stdout = bw.writer(); try stdout.print("Run `zig build test` to run the tests.\n", .{});
try bw.flush(); // don't forget to flush!}
test "simple test" { var list = std.ArrayList(i32).init(std.testing.allocator); defer list.deinit(); // try commenting this out and see if zig detects the memory leak! try list.append(42); try std.testing.expectEqual(@as(i32, 42), list.pop());}建置:
zig build執行:
zig build run你應該會看到回應:
All your codebase are belong to us.Run `zig build test` to run the tests.這邊要先特別介紹一下 print(),因為之後的範例會很常看到它。它用起來和 C 的差不多,每個 {} 都代表一個數值(就像 C 的 %d),後面的 .{ var },則是實際的變數或常數,如果有多個的話,要以前寫在 .{ } 內,並用逗號 , 分隔。如果沒有要填入數值的話 .{} 內留空。
// Value: 5std.debug.print("Value: {}\n", .{5});
// A: 5, B: 10std.debug.print("A: {}, B: {}\n", .{5, 10});測試
以 test "name" {} 包圍的區塊是測試程式。你可以執行測試:
zig build test它應該不會有輸出。試著將 17 行的 defer list.deinit(); 註解掉再執行一次測試,應該會看到類似下面的回應:
Build Summary: 3/5 steps succeeded; 1 failed; 1/1 tests passed; 1 leaked (disable with --summary none)test transitive failure└─ run test 1/1 passed, 1 leakederror: the following build command failed with exit code 1:參考
本文以 Zig 0.13.0 為主。並同時發佈在: