TExcelTAD
Home › Zig › Zig Printing

Zig Printing

Printing is how you see what your program is doing. In this course we use std.debug.print, which formats text and writes it to standard error. It never fails (any write error is ignored), so you do not need try in front of it.

The basics

std.debug.print takes two arguments: a format string and a tuple of values written as .{ … }. Every {} placeholder in the format string is replaced by the next value.

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const apples = 7;
    const fruit = "pears";
    std.debug.print("No values here\n", .{});
    std.debug.print("I have {d} apples\n", .{apples});
    std.debug.print("{d} apples and {d} {s}\n", .{ apples, 3, fruit });
}
No values here
I have 7 apples
7 apples and 3 pears

Nothing adds a newline for you — end the format string with \n. The number of placeholders must match the number of values; a mismatch is a compile error, not a runtime surprise.

Format specifiers

The letter inside the braces says how to show the value:

Specifier Meaning Example value Output
{d} decimal number (integers and floats) 255 255
{s} string ([]const u8) "hi" hi
{c} a single byte as a character 'A' A
{x} / {X} hexadecimal 255 ff / FF
{b} binary 5 101
{o} octal 8 10
{e} scientific notation 1500.0 1.5e3
{any} default debug format for any value [3]u8{1,2,3} { 1, 2, 3 }
{t} the tag name of an enum or error Color.red red
{?d} an optional number (null if empty) null null
{} default format for simple values true true
zig · try it yourself
const std = @import("std");

pub fn main() void {
    const n = 255;
    std.debug.print("dec={d} hex={x} HEX={X} bin={b} oct={o}\n", .{ n, n, n, n, n });
    std.debug.print("char={c} sci={e}\n", .{ 'Z', 1500.0 });
    std.debug.print("bool={} list={any}\n", .{ true, [_]u8{ 1, 2, 3 } });
}
dec=255 hex=ff HEX=FF bin=11111111 oct=377
char=Z sci=1.5e3
bool=true list={ 1, 2, 3 }

Note: Since Zig 0.15, a slice such as a string must have an explicit specifier. {} with a string is a compile error: "cannot format slice without a specifier (i.e. {s}, {x}, {b64}, or {any})". Use {s} for text and {any} for other slices.

Width, alignment and precision

After the specifier, add : followed by an optional fill character, an alignment (< left, ^ centre, > right), a width and .precision:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    std.debug.print("[{d:>6}]\n", .{42});
    std.debug.print("[{d:<6}]\n", .{42});
    std.debug.print("[{d:0>6}]\n", .{42});
    std.debug.print("[{s:^9}]\n", .{"mid"});
    std.debug.print("[{s:*<8}]\n", .{"ab"});
    std.debug.print("[{d:.2}]\n", .{3.14159});
    std.debug.print("[{d:8.3}]\n", .{2.5});
}
[    42]
[42    ]
[000042]
[   mid   ]
[ab******]
[3.14]
[   2.500]

This makes tidy tables easy:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const names = [_][]const u8{ "Tea", "Coffee", "Juice" };
    const prices = [_]f64{ 2.5, 3.75, 4.0 };

    std.debug.print("{s:<8}|{s:>7}\n", .{ "Item", "Price" });
    for (names, prices) |name, price| {
        std.debug.print("{s:<8}|{d:>7.2}\n", .{ name, price });
    }
}
Item    |  Price
Tea     |   2.50
Coffee  |   3.75
Juice   |   4.00

Printing braces

To print a literal { or }, double it: {{ and }}.

zig
std.debug.print("a set: {{1, 2}}\n", .{}); // prints: a set: {1, 2}

stdout in real programs

std.debug.print goes to stderr, which is perfect for learning and debugging. Real command-line tools usually write their results to stdout. In Zig 0.15 you create a buffered writer for it and must remember to flush:

zig
var buffer: [1024]u8 = undefined;
var stdout_writer = std.fs.File.stdout().writer(&buffer);
const stdout = &stdout_writer.interface;

try stdout.print("Result: {d}\n", .{42});
try stdout.flush(); // without this, buffered text may never appear

Because writing to stdout can fail, those calls need try. The format specifiers are exactly the same as for std.debug.print.

Test yourself

Which specifier prints a []const u8 as text?

  1. {d}
  2. {c}
  3. {s}
  4. {}

What does std.debug.print("[{d:0>4}]", .{7}) print?

  1. [7000]
  2. [0007]
  3. [ 7]
  4. [7 ]

Why is the second argument of std.debug.print written as .{} even when there is nothing to insert?

  1. It is optional decoration
  2. The function always takes a tuple of arguments, possibly empty
  3. It flushes the output
  4. It adds a newline