Skip to content

Zig Comments

A comment is a note in your code for people. The compiler skips it. Comments are how you explain why code does something, leave a reminder for later, or switch a line off while you test something. Zig keeps this simple: there are only line comments, plus two special kinds that become documentation.

A comment starts with // and runs to the end of the line. You can put one on its own line or at the end of a line of code:

const std = @import("std");
pub fn main() void {
// Work out the price with tax.
const price = 20;
const tax = 5; // a flat 5, to keep the example simple
std.debug.print("Total: {d}\n", .{price + tax});
}

Output:

Total: 25

Both comments are ignored, so the program just adds the numbers and prints them.

Comments are also handy for switching code off without deleting it. Put // in front of a line and it stops running:

const std = @import("std");
pub fn main() void {
std.debug.print("Step 1\n", .{});
// std.debug.print("Step 2\n", .{});
std.debug.print("Step 3\n", .{});
}

Output:

Step 1
Step 3

Most editors do this for you: select some lines and press Ctrl+/ (Cmd+/ on a Mac) in VS Code to comment them in or out.

C, Java and JavaScript have /* ... */ comments that can span several lines. Zig doesn’t:

const std = @import("std");
pub fn main() void {
/* This won't work */
std.debug.print("hi\n", .{});
}
main.zig:4:5: error: expected statement, found '/'
/* This won't work */
^

For a longer note, just start each line with //:

// This function reads the settings file.
// If the file is missing, it falls back to the defaults,
// so the program can still start on a fresh install.

It’s a deliberate choice. The language reference on comments explains that without multiline comments, every line of Zig can be understood on its own. That makes Zig code easier for tools (and people) to read, because a line never secretly sits inside a comment that started fifty lines earlier.

// only starts a comment in code, not inside a string. A web address stays a web address:

const std = @import("std");
pub fn main() void {
const url = "https://ziglang.org"; // this part is a comment
std.debug.print("{s}\n", .{url});
}

Output:

https://ziglang.org

A comment that starts with exactly three slashes is a doc comment. It documents whatever comes right after it: a function, a constant, a struct or a struct field. Several /// lines in a row are joined into one longer comment.

const std = @import("std");
/// The most items a cart can hold.
const max_items = 10;
/// Returns the price in cents after a discount.
/// `percent` is how much to take off, from 0 to 100.
fn discounted(cents: u32, percent: u32) u32 {
return cents - cents * percent / 100;
}
pub fn main() void {
std.debug.print("{d} cents, up to {d} items\n", .{ discounted(2000, 25), max_items });
}

Output:

1500 cents, up to 10 items

To the compiler, doc comments mean nothing when it runs your program. Their job is to describe your code to other people: editors show them when you hover over a name (through ZLS, see Zig Tools & Setup), and Zig can turn them into a documentation website.

Doc comments work on struct fields and methods too:

const std = @import("std");
/// A rectangle, measured in pixels.
const Rect = struct {
/// Width in pixels.
width: u32,
/// Height in pixels.
height: u32, // a normal comment is fine here too
/// Returns the area of the rectangle.
fn area(self: Rect) u32 {
return self.width * self.height;
}
};
pub fn main() void {
const r = Rect{ .width = 3, .height = 4 };
std.debug.print("area = {d}\n", .{r.area()});
}

Output:

area = 12

You’ll learn structs in Zig Structs. For now, notice where each /// goes: on the line right above the thing it describes.

Because a doc comment has to describe something, Zig is strict about where you put it. Inside a function body, there’s nothing for it to attach to:

const std = @import("std");
pub fn main() void {
/// How many times to say hello.
const times = 2;
std.debug.print("{d}\n", .{times});
}
main.zig:4:5: error: expected statement, found 'a document comment'
/// How many times to say hello.
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A doc comment at the very end of a file, with nothing after it, is also an error:

const std = @import("std");
pub fn main() void {
std.debug.print("hi\n", .{});
}
/// Nothing comes after this.
main.zig:7:1: error: unattached documentation comment
/// Nothing comes after this.
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The fix is easy either way: inside functions, use //. Save /// for things declared at the top level and inside structs.

A comment that starts with //! is a top-level doc comment. It describes the whole file (in Zig, a file is a module). It has to come first, before any code:

//! Small helpers for working out prices.
//! Every amount is in cents, so there's no rounding trouble.
const std = @import("std");
/// Adds tax to a price, in cents.
fn withTax(cents: u32) u32 {
return cents + cents / 10;
}
pub fn main() void {
std.debug.print("{d}\n", .{withTax(1000)});
}

Output:

1100

You’ll see //! at the top of most files in Zig’s standard library. It’s the first thing to read when you open one.

Zig can build a documentation website from your doc comments. It’s still a young feature (the generated site is fairly bare, and it may change), but it works. Put your file in its own folder (Zig includes every .zig file next to it), then run:

Terminal window
zig build-lib -femit-docs -fno-emit-bin shapes.zig

That creates a docs folder with an index.html and a few files it loads. The page fetches those files when it opens, so most browsers won’t show it if you just double-click index.html. Serve the folder with any small local web server instead, for example:

Terminal window
python3 -m http.server -d docs

Then open http://localhost:8000 in your browser. -fno-emit-bin means “only make the docs, not a library file”.

The standard library’s own docs are made the same way. zig std opens them for your exact version.

Some quick habits that make comments worth reading:

  • Explain why, not what. count += 1; // add one to count tells the reader nothing new. count += 1; // the header row counts too does.
  • Keep them close and current. A comment that no longer matches the code is worse than no comment.
  • Mark unfinished work with // TODO:. It’s a common convention, and editors can list all of them.
  • Use /// for anything other people will call. Say what it does, what the inputs mean and what can go wrong.
const std = @import("std");
pub fn main() void {
const rows = 9;
// The file has a header line, which isn't a data row.
const lines = rows + 1;
// TODO: read the real row count from the file.
std.debug.print("{d} lines\n", .{lines});
}

Output:

10 lines

Make this program print only Ready and Go! by commenting out one line (don’t delete anything):

const std = @import("std");
pub fn main() void {
std.debug.print("Ready\n", .{});
std.debug.print("Steady\n", .{});
std.debug.print("Go!\n", .{});
}

Hint: put // at the start of the line you want to skip.

Show solution
const std = @import("std");
pub fn main() void {
std.debug.print("Ready\n", .{});
// std.debug.print("Steady\n", .{});
std.debug.print("Go!\n", .{});
}

Output:

Ready
Go!

The commented-out line is still in the file, so you can switch it back on by removing the //.

Write a function celsiusToFahrenheit that takes a temperature in Celsius (i32) and returns Fahrenheit (F = C * 9 / 5 + 32). Give it a /// doc comment, and give the file a //! comment. Print the result for 100.

Hint: //! goes on the very first line of the file. /// goes on the line right above fn.

Show solution
//! Temperature conversions.
const std = @import("std");
/// Converts a temperature from Celsius to Fahrenheit.
/// Uses whole numbers, so the result is rounded down.
fn celsiusToFahrenheit(c: i32) i32 {
return @divFloor(c * 9, 5) + 32;
}
pub fn main() void {
std.debug.print("100 C is {d} F\n", .{celsiusToFahrenheit(100)});
}

Output:

100 C is 212 F

The //! line describes the file and the /// lines describe the function. @divFloor divides and rounds down; Zig wants you to say how to round when dividing signed numbers (more on that in Zig Operators).

This program doesn’t compile. Fix it without removing the comment’s text:

const std = @import("std");
pub fn main() void {
/// The number of players in the game.
const players = 4;
std.debug.print("{d} players\n", .{players});
}

Hint: read the error. What’s allowed inside a function body?

Show solution
const std = @import("std");
pub fn main() void {
// The number of players in the game.
const players = 4;
std.debug.print("{d} players\n", .{players});
}

Output:

4 players

Doc comments can’t go inside a function, so the /// becomes a normal // comment. Another fix is to move players to the top level of the file, where a /// comment is allowed.

  • // starts a comment that runs to the end of the line. Use it for notes and to switch code off.
  • Zig has no /* */ block comments. Start each line with // instead.
  • /// (exactly three slashes) is a doc comment for the declaration right after it.
  • //! at the top of a file documents the whole file.
  • Doc comments must be attached to something: not inside a function body, not at the end of a file.
  • zig build-lib -femit-docs -fno-emit-bin file.zig builds a docs website from them.

Next up: Zig Output, the difference between std.debug.print and writing to stdout.

Quick check

1. How do you write a comment that spans three lines in Zig?
2. What does a /// comment do?
3. You put a /// comment above a const inside main. What happens?
4. Where does a //! comment go?