Zig Documentation Comments
Code tells the computer what to do. Documentation tells the next person (often you, in six months) how to use it without reading every line. Zig keeps documentation right next to the code: special comments that editors show when you hover over a name, and that Zig can turn into a small website. This page shows how to write those comments, how to add examples that are checked by zig test, and how to build and view the docs on Zig 0.17.1.
The two kinds of doc comment
Section titled “The two kinds of doc comment”You met these in Zig Comments. A quick reminder:
///(exactly three slashes) documents the declaration right after it: a function, a constant, a type or a field.//!documents the whole file. It goes at the very top, before any code.
Normal // comments are for whoever reads the source. Doc comments are for whoever uses your code, and they’re the only comments that end up in the generated docs. The language reference on doc comments has the exact rules: they can’t go inside a function body, and one left at the end of a file with nothing after it is a compile error.
Here’s a small file with both kinds, plus a test for each function:
//! Small helpers for working with text.//!//! Every function here works on bytes, so it's meant for ASCII text.
const std = @import("std");
/// Returns a copy of `text` with every letter in upper case.////// The caller owns the returned memory and must free it with `gpa`.////// Errors:/// - `error.OutOfMemory` if the allocation fails.pub fn upper(gpa: std.mem.Allocator, text: []const u8) ![]u8 { const out = try gpa.alloc(u8, text.len); for (text, out) |c, *o| o.* = std.ascii.toUpper(c); return out;}
test upper { const loud = try upper(std.testing.allocator, "hi"); defer std.testing.allocator.free(loud); try std.testing.expectEqualStrings("HI", loud);}
/// Counts the words in `text`, separated by spaces.pub fn countWords(text: []const u8) usize { var it = std.mem.tokenizeScalar(u8, text, ' '); var n: usize = 0; while (it.next()) |_| n += 1; return n;}
test "countWords on an empty string" { try std.testing.expectEqual(0, countWords(""));}Run the tests with zig test. We saved the file as main.zig for this run, which is why the test names start with main. (with text.zig they’d start with text.).
Output:
1/2 main.decltest.upper...OK2/2 main.test.countWords on an empty string...OKAll 2 tests passed.The rest of this page builds the docs for this file. Save it as text.zig in a folder of its own.
Doctests: examples that can’t go stale
Section titled “Doctests: examples that can’t go stale”Look at the two tests above. The second one has a name in quotes, like every test you’ve written so far. The first one is test upper, with the name of a declaration and no quotes. That’s a doctest.
A doctest is a normal test (zig test runs it, and the output calls it decltest), but it’s also attached to upper, and the generated docs show it under Example Usage on upper’s page. So your example code is checked every time you run the tests. An example in a comment can quietly go out of date; a doctest fails instead.
The reference’s doctests section gives good advice: keep a doctest short and focused on how a new user would call the function. It doesn’t replace the /// comment; it goes alongside it.
Build the docs for one file
Section titled “Build the docs for one file”For a single file, one command does it:
zig build-lib -femit-docs -fno-emit-bin text.zig-femit-docs asks for documentation, and -fno-emit-bin says “don’t build the library itself”. When we ran it on 0.17.1, it created a docs folder next to the file:
docs/ index.html main.js main.wasm sources.tarThat’s the whole docs site. It doesn’t contain a page per function: index.html loads a small WebAssembly program (main.wasm) that reads your source code from sources.tar and builds the pages in the browser.
View the docs with a local web server
Section titled “View the docs with a local web server”Because the page loads main.wasm and sources.tar, double-clicking index.html usually shows a page stuck on “Loading…”. Browsers don’t let a page opened from disk fetch other files. Serve the folder with any small web server instead. If you have Python:
python3 -m http.server -d docsThen open http://localhost:8000 in your browser. Any static file server works; there’s nothing Zig-specific about it.
When we opened our text docs in a browser, we saw:
- The home page: the
//!text at the top, then a list of functions with their///summaries. - On
upper’s page: the full doc comment, its parameters and error set, the doctest under “Example Usage”, and the source code. - A search box (press
s), and?for keyboard shortcuts.
Two details worth knowing:
- Doc comments are Markdown. In our test,
`text`became code, blank///lines became paragraph breaks, and the-lines became a bulleted list. - The lists only show
pubdeclarations. A private function with a///comment wasn’t listed on the home page. (Its page still existed if you typed its name into the address bar, so don’t put secrets in doc comments.)
A docs step in build.zig
Section titled “A docs step in build.zig”In a project, add a docs step to build.zig so anyone can run zig build docs. This is the setup we tested on 0.17.1 for a library whose root file is src/text.zig:
const std = @import("std");
pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{});
const lib = b.addLibrary(.{ .name = "text", .root_module = b.createModule(.{ .root_source_file = b.path("src/text.zig"), .target = target, .optimize = optimize, }), });
const install_docs = b.addInstallDirectory(.{ .source_dir = lib.getEmittedDocs(), .install_dir = .prefix, .install_subdir = "docs", });
const docs_step = b.step("docs", "Build the documentation"); docs_step.dependOn(&install_docs.step);}Here’s what each part does:
addLibrarydescribes the library. You don’t have to install it; we only want its docs.lib.getEmittedDocs()asks for the docs folder, which also tells Zig to generate it.addInstallDirectorycopies that folder intozig-out/docs.b.step("docs", ...)makes a step calleddocs, anddependOnconnects the copy to it. Without that last line,zig build docswould do nothing.
Then:
zig build docspython3 -m http.server -d zig-out/docszig build --help now lists docs Build the documentation under “Steps”. The Zig Build System page explains steps and dependOn in more detail.
Writing doc comments that help
Section titled “Writing doc comments that help”A doc comment’s job is to answer the questions a caller has before they read the code. For most functions, that’s:
- What does it do? One sentence, starting with a verb: “Returns…”, “Counts…”, “Writes…”.
- Who owns the memory? If it returns allocated memory, say who frees it and with which allocator. In Zig this is the most useful sentence you can write.
- What can go wrong? Which errors it returns, and when.
- What must the caller promise? Rules like “
indexmust be less thanlen”.
The reference’s doc comment guidance adds a few rules of its own:
- Don’t repeat what the name says.
/// Gets the name.abovefn getNameis noise. Spend the words on what isn’t obvious. - Repeating yourself across similar functions is fine. Someone hovering over
readU16won’t see the comment onreadU32. - “Assume” and “assert” mean different things. Write “asserts” when breaking the rule is caught in safe builds (it panics), and “assumes” when it isn’t checked at all (illegal behavior). A caller reading “assumes” knows to be careful.
Here’s a before and after:
// Before: says nothing the code doesn't/// This function gets an item from the list by its index.pub fn get(self: List, index: usize) T { ... }
// After: says what the caller needs to know/// Returns the item at `index`./// Asserts that `index` is less than `self.len()`.pub fn get(self: List, index: usize) T { ... }And a few things to leave out of doc comments: how the function works inside (that’s for // comments in the body), history (“changed in v2”) and TODO notes. Those belong in normal comments or your commit messages.
Practice
Section titled “Practice”1. Add the missing doc comments
Section titled “1. Add the missing doc comments”Give this file a //! comment, and give celsiusToFahrenheit a /// comment that says what it does and how it rounds. Then check it still runs.
const std = @import("std");
pub fn celsiusToFahrenheit(c: i32) i32 { return @divFloor(c * 9, 5) + 32;}
pub fn main() void { std.debug.print("{d}\n", .{celsiusToFahrenheit(37)});}Hint: //! goes on the first line, /// right above pub fn. The result is a whole number, so say how fractions are handled.
Show solution
//! Temperature conversions for whole-degree values.
const std = @import("std");
/// Converts a temperature from Celsius to Fahrenheit./// The result is rounded down to a whole degree.pub fn celsiusToFahrenheit(c: i32) i32 { return @divFloor(c * 9, 5) + 32;}
pub fn main() void { std.debug.print("{d}\n", .{celsiusToFahrenheit(37)});}Output:
9837 °C is 98.6 °F, so the rounding note matters: without it, a caller might expect 99. That’s the kind of detail a doc comment is for.
2. Turn an example into a doctest
Section titled “2. Turn an example into a doctest”The comment below has an example in it. Move the example into a doctest, so it’s checked by zig test, and keep the /// comment short.
/// Returns the larger of two numbers./// Example: max(3, 7) returns 7.pub fn max(a: i32, b: i32) i32 { return if (a > b) a else b;}Hint: a doctest is test max { ... }, with the declaration’s name and no quotes.
Show solution
const std = @import("std");
/// Returns the larger of two numbers.pub fn max(a: i32, b: i32) i32 { return if (a > b) a else b;}
test max { try std.testing.expectEqual(7, max(3, 7));}Running zig test max.zig prints:
1/1 max.decltest.max...OKAll 1 tests passed.In the generated docs, the test shows up under “Example Usage” on max’s page. If someone breaks max, the example fails instead of lying.
3. Build and open the docs
Section titled “3. Build and open the docs”Build the docs for your solution to exercise 1 and open them in a browser. What shows up on the home page?
Hint: two commands: one to build, one to serve.
Show solution
zig build-lib -femit-docs -fno-emit-bin temperature.zigpython3 -m http.server -d docsOpen http://localhost:8000. The home page shows the //! sentence and celsiusToFahrenheit with its doc comment. main is pub too, so it’s listed as well. In a real library you’d keep main in a separate file, so the docs only show the functions people should call.
///documents the next declaration;//!documents the whole file. Both are Markdown.- A doctest (
test name { ... }, no quotes) is a test that also shows up as “Example Usage” in the docs. zig build-lib -femit-docs -fno-emit-bin file.zigwrites adocsfolder; in a project, add adocsstep withgetEmittedDocs()andaddInstallDirectory.- The docs are a small web app: view them through a local web server, not by double-clicking.
- Only
pubdeclarations are listed.zig stdshows the standard library’s docs the same way. - A good doc comment says what it does, who owns the memory, what can fail, and uses “asserts” or “assumes” for the caller’s rules.
Next up: Zig Upgrading Between Versions, how to pin a Zig version, read release notes and move old code to 0.17.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Doc comments in the language reference: where
///is allowed, with the exact errors. - Top-level doc comments: how
//!documents a file. - Doctests: tests that double as examples in the docs.
- Doc comment guidance: the style guide’s rules, including “assume” and “assert”.
- Zig standard library docs (0.17.1): the biggest real example of generated Zig docs.