Zig Keywords
Zig has a small set of keywords: 46 in Zig 0.17.1, the same list as the Keyword Reference in the language reference (we also checked it against the compiler’s own tokenizer). Many of them you’ve used on every page of this tutorial; a few are for low-level work you may never need. This page lists all of them, grouped by what they do, with a plain one-line meaning and a link to the lesson that teaches each one.
Most of them in one program
Section titled “Most of them in one program”Here’s a small program that uses most of the everyday keywords. Each one is explained in the tables below:
const std = @import("std");
pub const Shape = union(enum) { circle: f64, square: f64,};
const Size = enum { small, large };
fn area(shape: Shape) f64 { return switch (shape) { .circle => |r| std.math.pi * r * r, .square => |s| s * s, };}
fn parse(text: []const u8) !u32 { if (text.len == 0) return error.Empty; return std.fmt.parseInt(u32, text, 10);}
fn first(items: []const u32) ?u32 { return if (items.len > 0) items[0] else null;}
pub fn main() !void { defer std.debug.print("done\n", .{});
var total: f64 = 0; for ([_]Shape{ .{ .circle = 1 }, .{ .square = 2 } }) |s| total += area(s); std.debug.print("area {d:.2}\n", .{total});
const n = try parse("42"); const bad = parse("") catch 0; const start = first(&.{}) orelse 7; std.debug.print("{d} {d} {d}\n", .{ n, bad, start });
var i: u32 = 0; while (true) : (i += 1) { if (i == 1) continue; if (i > 2 and n > 0) break; }
const size: Size = if (n > 10 or bad > 0) .large else .small; const twice = comptime 2 * 21; std.debug.print("{t} {d} {d}\n", .{ size, i, twice });}
test "parse" { try std.testing.expectEqual(42, try parse("42"));}Output:
area 7.1442 0 7large 3 42doneThat’s const, pub, union, enum, fn, return, switch, if, else, error, try, catch, orelse, defer, var, for, while, continue, break, and, or, comptime and test: 23 keywords, half the language’s list.
Declarations
Section titled “Declarations”| Keyword | What it means | Lesson |
|---|---|---|
const |
Declares a name whose value can’t change. On a pointer (*const T), the pointed-to value can’t be changed through it. |
Zig Variables |
var |
Declares a variable that can change. | Zig Variables |
pub |
Makes a top-level declaration visible from other files. | Zig Modules & Imports |
fn |
Declares a function, or a function type. | Zig Functions |
test |
Declares a test block, which only zig test compiles and runs. |
Zig Testing |
threadlocal |
Gives each thread its own copy of a global variable. | Thread-local variables (reference) |
| Keyword | What it means | Lesson |
|---|---|---|
struct |
Defines a struct: named fields plus functions and constants. | Zig Structs |
enum |
Defines an enum: a type with a fixed list of named values. | Zig Enums |
union |
Defines a union; union(enum) makes a tagged union. |
Zig Tagged Unions |
opaque |
Defines a type with unknown size and layout, usually a handle from C. | Zig Opaque Types |
error |
Defines an error set (error{ NotFound }) or a single error (error.NotFound). |
Zig Errors |
packed |
Gives a struct a bit-exact layout with no padding. | Zig Packed & Extern Structs |
anytype |
A parameter type meaning “any type, inferred from the call”. | Zig Function Parameters |
Control flow
Section titled “Control flow”| Keyword | What it means | Lesson |
|---|---|---|
if |
Runs code when a condition is true, or unwraps an optional or error union with a capture. | Zig If…Else |
else |
The other branch of an if, switch, while or for. |
Zig If…Else |
switch |
Picks a branch by value. It must handle every possible value. | Zig Switch |
while |
Loops while a condition is true, or while an optional has a value. | Zig While |
for |
Loops over arrays, slices and ranges like 0..10. |
Zig For |
break |
Leaves a loop, or leaves a labeled block with a value. | Zig Break/Continue |
continue |
Jumps to the next pass of a loop. | Zig Break/Continue |
return |
Leaves a function, with a value if it has one. | Zig Functions |
defer |
Runs an expression when the current block ends, however it ends. | Zig Defer |
unreachable |
Says “this can never happen”. In debug and safe builds, reaching it panics. |
Zig Unreachable |
inline |
On a loop, unrolls it at compile time; on a function, inlines it at every call. | Zig Inline Functions |
noinline |
The opposite: the function must never be inlined. | Zig Inline Functions |
Errors and optionals
Section titled “Errors and optionals”| Keyword | What it means | Lesson |
|---|---|---|
try |
Unwraps an error union, or returns the error from the current function. | Zig Try & Catch |
catch |
Gives a fallback value or block when an expression is an error. | Zig Try & Catch |
errdefer |
Like defer, but runs only if the function returns an error. |
Zig Errdefer |
orelse |
Gives a fallback value when an optional is null. |
Zig Optionals |
Logic and comptime
Section titled “Logic and comptime”| Keyword | What it means | Lesson |
|---|---|---|
and |
Boolean AND. Skips the right side if the left is false. |
Zig Booleans |
or |
Boolean OR. Skips the right side if the left is true. |
Zig Booleans |
comptime |
Makes a parameter, variable or expression known (or run) at compile time. | Zig Comptime |
! (not) is an operator, not a keyword. And Zig has no && for booleans: you write and and or. (|| does exist, but it merges error sets.)
Pointers and memory
Section titled “Pointers and memory”| Keyword | What it means | Lesson |
|---|---|---|
align |
Sets the alignment of a variable, function or pointer type: align(16). |
Alignment (see Read more) |
allowzero |
Lets a pointer type hold address 0, which normal pointers can’t. Mostly for embedded and OS code. | allowzero (reference) |
volatile |
Every read and write through this pointer really happens, for hardware registers. Also marks asm with side effects. |
Zig Embedded |
noalias |
Promises that a pointer parameter doesn’t overlap with other pointers, so the compiler can optimize more. The reference has no entry for it yet. | (none yet) |
addrspace |
Puts a pointer in a specific address space, for targets with more than one, such as GPUs and AVR chips. The reference has no entry for it yet. | (none yet) |
C, linking and low-level code
Section titled “C, linking and low-level code”| Keyword | What it means | Lesson |
|---|---|---|
extern |
Declares a function or variable that comes from elsewhere (like a C library); also extern struct for C layout. |
Zig and C |
export |
Makes a function or variable visible to C and other languages in the compiled output. | Zig Exporting to C |
callconv |
Sets a function’s calling convention, such as callconv(.c) for a callback that C will call. |
Zig and C |
linksection |
Puts a function or global variable in a named section of the output, like .data. |
Zig Embedded |
asm |
Starts an inline assembly expression. | Zig Inline Assembly |
Reserved for the old async
Section titled “Reserved for the old async”| Keyword | What it means | Lesson |
|---|---|---|
anyframe |
Was the type of an async function frame. | Zig Async & Futures |
suspend |
Was used to pause an async function. | Zig Async & Futures |
resume |
Was used to continue a paused async function. | Zig Async & Futures |
nosuspend |
Was used to mark code that never suspends. | Zig Async & Futures |
These four belong to the async functions Zig had before the self-hosted compiler. They’re still keywords, so you can’t use them as names, but the feature doesn’t work in 0.17.1:
pub fn main() void { suspend {}}main.zig:2:5: error: async has not been implemented in the self-hosted compiler yet suspend {} ^~~~~~~~~~Today, concurrency goes through std.Io instead: io.async(f, .{args}) returns a future you await. See Zig Async & Futures.
Words that are not keywords
Section titled “Words that are not keywords”Some words look like keywords but aren’t on the list.
true, false, null, undefined and the type names (u8, bool, type and so on) are primitives: built-in values and types. You can’t use them as variable names either, but the error is different, and it suggests the fix:
pub fn main() void { const null = 1; _ = null;}main.zig:2:11: error: name shadows primitive 'null' const null = 1; ^~~~main.zig:2:11: note: consider using @"null" to disambiguateasync, await and usingnamespace used to be keywords. They were removed (in 0.15), so now they’re ordinary names:
const std = @import("std");
pub fn main() void { const async = 1; const await = 2; const usingnamespace = 3; std.debug.print("{d}\n", .{async + await + usingnamespace});}Output:
6That’s why old code with async foo() gives a confusing “expected ‘;’” error instead of a message about async. See Zig Upgrading.
Builtins like @import or @as start with @, so they can never clash with your names. Zig Builtin Functions covers the common ones.
Using a keyword as a name
Section titled “Using a keyword as a name”Sometimes you need a keyword as a name, for example a struct field that must match a JSON key called "test" or "export". Write it as @"...", which the reference calls an identifier in string form:
const std = @import("std");
const Request = struct { @"test": bool, @"export": []const u8,};
pub fn main() void { const r: Request = .{ .@"test" = true, .@"export" = "csv" }; std.debug.print("{} {s}\n", .{ r.@"test", r.@"export" });}Output:
true csvWithout the @"...", const fn = 1; fails with expected 'an identifier', found 'fn'. Field names that are only primitives, like type, don’t need it: zig fmt even removes @"type" for you. See Zig Style Guide.
- Zig 0.17.1 has 46 keywords, listed in the reference’s Keyword Reference.
- About half are everyday words:
const,var,fn,pub,if,else,switch,for,while,return,try,catch,defer,struct,enum,unionand friends. - The rest are for C interop, linking and low-level work (
extern,export,callconv,align,volatile,asm), plus four reserved for the old async that don’t work any more. true,null,undefinedand type names are primitives, not keywords;async,awaitandusingnamespaceare plain names now.- Use
@"name"when you need a keyword as a name.
You’ve reached the end of the tutorial. Thank you for reading it all the way through. Go build something, and when it breaks in an interesting way, the lessons are still here. The Zig Next Steps page has ideas for what to do now.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Keyword Reference: the official list, with a short description and links for each keyword.
- Identifiers: the rules for names, including the
@"..."form. - Primitive types and values: the built-in types and values that aren’t keywords.
- Alignment: what
alignchanges for variables, functions and pointers. - Grammar: the full grammar, if you want to see exactly where each keyword can go.