Skip to content

Printing Values

The function std.debug.print writes text.

The function std.debug.print writes text.

const std = @import("std");

pub fn main() void {
    std.debug.print("hello\n", .{});
}

The first argument is the format string.

"hello\n"

The second argument is a tuple of values.

.{}

When there are no values to print, the tuple is empty.

To print an integer, put {d} in the format string:

const std = @import("std");

pub fn main() void {
    const n = 42;

    std.debug.print("n = {d}\n", .{n});
}

The output is:

n = 42

The {d} is a placeholder. It says that an integer value should be printed in decimal form.

The value comes from the tuple:

.{n}

To print more than one value, put more values in the tuple:

const std = @import("std");

pub fn main() void {
    const x = 10;
    const y = 20;

    std.debug.print("x = {d}, y = {d}\n", .{ x, y });
}

The output is:

x = 10, y = 20

The placeholders are matched with the tuple values from left to right.

The first {d} uses x.

The second {d} uses y.

To print a string, use {s}:

const std = @import("std");

pub fn main() void {
    const name = "zig";

    std.debug.print("hello, {s}\n", .{name});
}

The output is:

hello, zig

To print a value in its default form, use {any}:

const std = @import("std");

pub fn main() void {
    const ok = true;

    std.debug.print("{any}\n", .{ok});
}

The output is:

true

{any} is useful while exploring. More specific formats are better in finished code.

A newline is written with \n:

std.debug.print("one\ntwo\n", .{});

The output is:

one
two

The backslash begins an escape sequence. The sequence \n means newline.

A common mistake is to forget the tuple:

std.debug.print("hello\n");

This is wrong. The function still expects the second argument.

Write:

std.debug.print("hello\n", .{});

Another common mistake is to give the wrong number of values:

std.debug.print("{d} {d}\n", .{10});

The format string asks for two values. The tuple provides one. The compiler reports the error.

Printing is not the center of Zig, but it is the easiest way to see what a program is doing. Use it freely while learning.

Exercise 1-13. Print your name with {s}.

Exercise 1-14. Print two integers on one line.

Exercise 1-15. Print three lines with one call to std.debug.print.

Exercise 1-16. Write a format string with two placeholders and pass only one value. Read the compiler error.