Syntax Basics, Comments and Style
addrspace align allowzero and anyframe anytype asm break callconv catch comptime const continue defer else enum errdefer error export extern fn for if inline linksection noalias noinline nosuspend opaque or orelse packed pub resume return struct suspend swi…
3.1 Program Structure
Statements end with ;. Blocks use {}. Indentation is 4 spaces (zig fmt enforces the canonical style).
Order-independent top-level declarations: functions and constants can be used before they're defined.
Every file is a struct. Top-level declarations are the struct's members.
const std = @import("std"); // import the standard library
const math = std.math; // alias a namespace
const max_users = 100; // top-level constant (container-level declaration)
pub fn main() void { // `pub` = visible to other files
const x: i32 = 5;
std.debug.print("{d}\n", .{x});
}3.2 Comments
There are no multi-line comments in Zig. This is deliberate: each line can be tokenized independently.
// Normal comment
/// Doc comment for the following declaration (shows up in generated docs)
pub fn add(a: i32, b: i32) i32 {
return a + b;
}
//! Top-level doc comment (describes the current module/file); must be at the start of the file3.3 Identifiers and Naming Style
Types (structs, enums, unions, type-returning functions) ArrayList, Point readFile, parseInt
Variables, constants, fields, parameters max_len, user_id Files that are types (have fields) Files that are namespaces
@"any identifier" syntax allows otherwise invalid names (keywords, C symbols): const @"type" = 5;.
3.4 Keywords
addrspace align allowzero and anyframe anytype asm break callconv catch comptime const continue defer else enum errdefer error export extern fn for if inline linksection noalias noinline nosuspend opaque or orelse packed pub resume return struct suspend switch test threadlocal try union unreachable var volatile while
3.5 Unused Variables Are Errors
Unused locals, parameters, and imports are compile errors. Discard explicitly with _ = value;.
Unused function results are also errors unless discarded: _ = compute();.