Skip to content

Zig Style Guide

Zig code from different people tends to look the same, and that’s on purpose. Layout is handled by one tool, zig fmt, so nobody argues about spaces and braces. Naming follows a short official guide that ships inside the language reference’s Style Guide. The compiler doesn’t enforce the naming rules, but the standard library follows them, and so does most Zig code you’ll read. Learn them once and other people’s code gets much easier to read.

Here’s a file typed in a hurry. It compiles, but it’s hard to read:

const std=@import("std");
const Point=struct{x:i32,y:i32,
fn add(a:Point,b:Point)Point{return .{.x=a.x+b.x,.y=a.y+b.y};}};
pub fn main() void
{
const p=Point.add(.{.x=1,.y=2},.{.x=3,.y=4});
const names = [_][]const u8{"ann","bob","cy",};
std.debug.print("{d},{d} {d}\n",.{p.x,p.y,names.len});
}

Run zig fmt on it:

Terminal window
zig fmt main.zig

It prints the name of each file it changed (main.zig), and the file now looks like this:

const std = @import("std");
const Point = struct {
x: i32,
y: i32,
fn add(a: Point, b: Point) Point {
return .{ .x = a.x + b.x, .y = a.y + b.y };
}
};
pub fn main() void {
const p = Point.add(.{ .x = 1, .y = 2 }, .{ .x = 3, .y = 4 });
const names = [_][]const u8{
"ann",
"bob",
"cy",
};
std.debug.print("{d},{d} {d}\n", .{ p.x, p.y, names.len });
}

Output:

4,6 3

Look at what changed: four-space indents, spaces around = and operators, the opening brace moved up onto the fn line, spaces inside .{ }, and one statement per line. zig fmt never changes what the program does, only how it looks.

Now look at the two lists. The names list got one item per line, but .{ p.x, p.y, names.len } stayed on one line. The difference is the trailing comma: "cy", ended with a comma in the messy version, and that’s how you tell zig fmt “put each item on its own line”. The Point fields were split up for the same reason (y:i32,). So you choose the layout of a list by adding or removing that last comma, and zig fmt does the rest.

A few more things worth knowing:

  • zig fmt . formats every .zig file in the folder and below.
  • zig fmt --check . changes nothing. It lists the files that aren’t formatted and exits with an error, which is handy in CI.
  • It also cleans up the file itself: it turned Windows line endings (\r\n) into plain \n when we tried it, and it removes a byte order mark.
  • It fixes some old code for you. On 0.17 it rewrites the deprecated @intFromEnum and @enumFromInt into the new @backingInt and @fromBackingInt. See Zig Upgrading.
  • For the rare block you really want laid out by hand, put it between // zig fmt: off and // zig fmt: on. You’ll almost never need it: zig fmt already keeps rows like a 3×3 grid of numbers lined up the way you typed them.

The reference’s whitespace section is short, and zig fmt does most of it for you:

  • 4 spaces to indent. No tabs.
  • Opening braces on the same line, unless you need to wrap.
  • If a list has more than 2 items, put each on its own line and end with a trailing comma.
  • Aim for lines of about 100 characters, and use common sense.

The line length is the only one zig fmt won’t fix. If a call gets too long, add a trailing comma to its argument list and zig fmt will split it up.

Roughly: camelCaseFunctionName, TitleCaseTypeName, snake_case_variable_name. Here’s the whole set in one program:

const std = @import("std");
// snake_case: variables, constants, fields
const max_players = 4;
// TitleCase: types
const HttpRequest = struct {
method: []const u8,
path: []const u8,
// camelCase: functions
fn isGet(self: HttpRequest) bool {
return std.mem.eql(u8, self.method, "GET");
}
};
// TitleCase: a function that returns a type
fn Grid(comptime T: type, comptime size: usize) type {
return [size][size]T;
}
pub fn main() void {
const request: HttpRequest = .{ .method = "GET", .path = "/" };
const board: Grid(u8, 3) = @splat(@splat(0));
std.debug.print("{} {d} {d}\n", .{ request.isGet(), board.len, max_players });
}

Output:

true 3 4

The precise rules from the reference’s Names section go in this order. Ask the questions top to bottom and stop at the first “yes”:

If the name is… Use Examples
a struct with no fields that you never create (a “namespace”) snake_case std.mem, json
a type or a type alias TitleCase HttpRequest, ArrayList
a function that returns a type TitleCase Grid, std.ArrayList, std.AutoHashMap
any other function camelCase isGet, readFileAlloc
anything else (variables, constants, fields, parameters) snake_case max_players, host_name

Two details trip people up:

  • Constants are snake_case too, not SCREAMING_CASE like in C or Python: const max_players = 4;, not MAX_PLAYERS.
  • Functions that return a type are TitleCase, because using them reads like a type: std.ArrayList(u8).

Acronyms follow the same rules as any other word, even two-letter ones. So it’s XmlParser, not XMLParser; HttpRequest, not HTTPRequest; and readU32Be, not readU32BE. A constant holding an XML document is xml_document.

The guide adds one sensible exception: if there’s an established name, like the C error code ENOENT, keep it as it is.

In Zig, a file is a struct. That gives a simple rule for file names:

  • A file that has top-level fields is a type, so it’s TitleCase. In the standard library, Io.zig, Thread.zig and heap/ArenaAllocator.zig are files like this.
  • Every other file is a namespace, so it’s snake_case: array_list.zig, hash_map.zig, main.zig.
  • Folders are always snake_case.

A “file that is a type” starts like this, with its fields at the top level (this is the real start of heap/ArenaAllocator.zig, cut short):

//! This allocator takes an existing allocator, wraps it, and provides an interface where
//! you can allocate and then free it all together. ...
const ArenaAllocator = @This();
child_allocator: Allocator,
state: State,

You’ll see more about files as structs in Zig Modules & Imports.

This part of the guide is about what goes into a name, and it’s the part people forget.

Don’t use words that apply to everything. The guide lists Value, Data, Context, Manager, State, and file names like utils, misc or somebody’s initials. Its reasoning: everything is a value, all types are data, all logic manages state, so the word tells the reader nothing. UserData is just User. A utils.zig full of unrelated helpers is a sign they haven’t found their real home yet.

Don’t repeat the namespace. Every declaration has a full name that includes its file and any structs around it. Choose names that read well in that full form:

const std = @import("std");
pub const json = struct {
pub const JsonValue = union(enum) {
number: f64,
boolean: bool,
};
};
pub const csv = struct {
pub const Value = union(enum) {
number: f64,
text: []const u8,
};
};
pub fn main() void {
std.debug.print("{s}\n", .{@typeName(json.JsonValue)});
std.debug.print("{s}\n", .{@typeName(csv.Value)});
}

Output:

main.json.JsonValue
main.csv.Value

json.JsonValue says “json” twice. csv.Value reads naturally. That’s the same reason the standard library has std.json.Value and std.Io.Writer, not std.json.JsonValue or std.Io.IoWriter. (Notice that Value is fine here, even though it’s on the “avoid” list: inside csv, “a csv value” is exactly what it is, and there’s no more precise name. The guide calls this out as the exception.)

In some languages _name means “private” or “don’t touch”. Zig has no private fields, and the guide says not to pretend otherwise. Give fields clear names, and write in the doc comment how they should be used.

If a name clashes with a keyword, use the @"..." syntax instead of an underscore:

const std = @import("std");
const Result = struct {
@"error": bool,
message: []const u8,
};
pub fn main() void {
const r: Result = .{ .@"error" = true, .message = "disk full" };
std.debug.print("{} {s}\n", .{ r.@"error", r.message });
}

Output:

true disk full

error is a keyword, so the field needs @"error". Names like type are not keywords, just primitive type names, and they can be used as field names directly. When we tried writing @"type" as a field name, zig fmt rewrote it to plain type.

The style guide has four short rules for /// comments (the doc comment guidance):

  • Leave out anything the name already says. /// Returns the length. above fn len() adds nothing.
  • Repeating information on similar functions is fine. Editors show the comment of the one function you hover over, so each needs to make sense alone.
  • Use the word “assume” for a rule the caller must follow that is not checked: breaking it is unchecked illegal behavior.
  • Use the word “assert” for a rule that is checked in safe builds: breaking it panics.
/// Returns the item at `index`.
/// Asserts that `index` is less than `len`.
pub fn get(self: List, index: usize) T {
std.debug.assert(index < self.len);
return self.items[index];
}

Zig Documentation Comments covers writing them in more depth, and how to turn them into a website.

The style guide doesn’t fix the order of things in a file, but most Zig code, including the standard library and the zig init template, follows the same pattern:

//! What this file is for, in a sentence or two.
const std = @import("std");
const Allocator = std.mem.Allocator; // short aliases you use a lot
/// Public things first: what other files will use.
pub const Shape = union(enum) {
circle: f64,
square: f64,
};
pub fn area(shape: Shape) f64 {
return switch (shape) {
.circle => |r| std.math.pi * r * r,
.square => |s| s * s,
};
}
// Private helpers after the code that uses them (order doesn't matter to Zig).
test area {
try std.testing.expectEqual(4, area(.{ .square = 2 }));
}
  1. A //! comment that says what the file is for.
  2. Imports, with std first.
  3. The public API, then private helpers.
  4. Tests, either at the bottom or right after the function they test.

Zig doesn’t care about the order of top-level declarations, so this is only for people. Pick a layout and keep it the same across your project.

This program compiles, but almost every name breaks the style guide. Fix the names (and nothing else):

const std = @import("std");
const DEFAULT_PORT = 8080;
const server_config = struct {
HostName: []const u8,
port: u16 = DEFAULT_PORT,
fn print_url(self: server_config) void {
std.debug.print("http://{s}:{d}/\n", .{ self.HostName, self.port });
}
};
pub fn main() void {
const Config: server_config = .{ .HostName = "localhost" };
Config.print_url();
}

Hint: go through the table above. A constant is still snake_case, a struct is a type, and a method is a function.

Show solution
const std = @import("std");
const default_port = 8080;
const ServerConfig = struct {
host_name: []const u8,
port: u16 = default_port,
fn printUrl(self: ServerConfig) void {
std.debug.print("http://{s}:{d}/\n", .{ self.host_name, self.port });
}
};
pub fn main() void {
const config: ServerConfig = .{ .host_name = "localhost" };
config.printUrl();
}

Output:

http://localhost:8080/

DEFAULT_PORT becomes default_port, the struct becomes ServerConfig, the field host_name, the method printUrl, and the local config.

You want this array to have one name per line. Without typing any new lines, what single character do you add before running zig fmt?

const team = [_][]const u8{ "Ana", "Ben", "Cy" };

Hint: read the trailing comma part of the first section again.

Show solution

Add a comma after the last item:

const team = [_][]const u8{ "Ana", "Ben", "Cy", };

zig fmt then lays it out as:

const team = [_][]const u8{
"Ana",
"Ben",
"Cy",
};

Remove the comma (and join the lines) to get the one-line version back.

Suggest better names for these: const UserData = struct { ... } in user.zig, pub const http = struct { pub const HttpClient = ... }, and a file called misc.zig that holds a slugify function.

Hint: words that fit every type say nothing, and a name shouldn’t repeat its namespace.

Show solution
  • UserData becomes User. “Data” fits every type.
  • http.HttpClient becomes http.Client. The full name already says “http”.
  • misc.zig is a sign slugify hasn’t found its home. Move it next to the code that uses it, or into a file named after what it does, like slug.zig or text.zig.
  • zig fmt handles layout: 4-space indents, braces on the same line, spacing. zig fmt --check . is for CI.
  • A trailing comma tells zig fmt to put each item of a list on its own line.
  • Names: camelCase functions, TitleCase types and type-returning functions, snake_case for everything else, constants included.
  • Acronyms are words: XmlParser, HttpRequest. Files with top-level fields are TitleCase, other files and folders snake_case.
  • Avoid redundant names: no Data, Manager or utils, and no repeating the namespace (json.Value, not json.JsonValue).
  • No _private prefixes; use @"..." for keyword clashes. In doc comments, “assume” means unchecked and “assert” means checked.

Next up: Zig Documentation Comments, writing /// and //! comments that help, and turning them into a website.

Quick check

1. How should a function that returns a type be named?
2. What is the Zig-style name for a constant holding the maximum number of retries?
3. Inside a namespace called json, which type name follows the guide?