Getting Started
Hello World
Zig uses @import for std lib; print uses comptime format strings.
const std = @import("std");
pub fn main() void {
std.debug.print("Hello, {s}\n", .{"World"}});
}Variables
const is immutable, var is mutable. Types are explicit or inferred.
const x: i32 = 10;
var y: i32 = 20;
y += 5;Functions
Functions use fn keyword; pub makes them public.
fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn main() void {
const std = @import("std");
std.debug.print("{d}\n", .{add(3, 4)});
}Build
Zig has a built-in build system and cross-compilation.
# zig build-exe main.zig
# zig run main.zigTypes
Integers
Zig has arbitrary bit-width integers: i8, u8, i16, u16, i32, u32, etc.
const a: u8 = 255;
const b: i32 = -100;
const c: usize = 0;Arrays
[_] infers array length.
const arr = [_]i32{ 1, 2, 3, 4, 5 };
const first = arr[0];
const len = arr.len;Slices
Slices are views into arrays; .. is exclusive end.
const arr = [_]i32{ 1, 2, 3, 4, 5 };
const slice = arr[1..4]; // [2, 3, 4]Optionals
?T is optional type; use .? or if-let to unwrap.
var maybe: ?i32 = null;
maybe = 42;
if (maybe) |val| {
// val is i32 here
}Control Flow
If-Else
If-else are expressions in Zig.
const x: i32 = 5;
if (x > 3) {
// big
} else {
// small
}Switch
Switch must be exhaustive.
const x: u8 = 2;
switch (x) {
1 => {},
2 => {},
else => {},
}While
The : (i += 1) is the continue expression.
var i: u32 = 0;
while (i < 5) : (i += 1) {
// loop body
}For
For iterates over slices/arrays.
const arr = [_]i32{ 1, 2, 3 };
for (arr) |val| {
// use val
}Memory
Allocators
Zig has no hidden allocations; allocators are explicit.
const std = @import("std");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
const slice = try allocator.alloc(u8, 100);
defer allocator.free(slice);
}Defer
defer runs at scope exit — RAII-like resource cleanup.
const std = @import("std");
pub fn main() void {
const file = std.fs.cwd().createFile("test.txt", .{}) catch unreachable;
defer file.close();
}Was this helpful?