Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 37 ยท Getting Started

Your First Zig Program

Write, run and understand your first Zig program: the std import, pub fn main, std.debug.print format strings, and writing to standard output with the 0.15 writer.

Every language starts with printing a line of text. In Zig this tiny program also introduces imports, functions, string literals, format placeholders and anonymous tuples. We will take it apart piece by piece, so that the rest of the course never contains a mystery token.

Create a file called hello.zig and type this:

ZIG
const std = @import("std");

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

Run it with:

TEXT
zig run hello.zig

The compiler builds the program in a cache folder and runs it. You will see Hello, world! in the terminal.

Line by line

const std = @import("std"); declares a constant named std and sets it to the result of the builtin function @import. Builtins start with @ and are provided by the compiler. @import("std") returns the standard library, which Zig treats as a struct full of functions and types. Unlike C's #include, @import does not paste text: it gives you a value you can name anything you like.

pub fn main() void { defines a function. fn introduces it, main is the name the runtime starts, the empty parentheses mean no parameters, and void is the return type, meaning "nothing". pub makes the function visible outside this file, and the start-up code needs to see main.

std.debug.print("Hello, world!\n", .{}); calls the function print found in std.debug. The first argument is a format string; the second is a tuple of values to insert. Here there are none, so we pass the empty tuple .{}. It always needs a second argument, even if it is empty.

Format placeholders

std.debug.print fills {} placeholders from the tuple. Types and options go after a colon:

ZIG
const std = @import("std");

pub fn main() void {
    const name = "Zig";
    const year: u32 = 2016;
    const pi: f64 = 3.14159;

    std.debug.print("{s} appeared in {d}\n", .{ name, year });
    std.debug.print("pi is about {d:.2}\n", .{pi});
    std.debug.print("hex {x}, binary {b}, char {c}\n", .{ 255, 5, 'A' });
    std.debug.print("any value: {any}\n", .{[_]u8{ 1, 2, 3 }});
}

This prints:

TEXT
Zig appeared in 2016
pi is about 3.14
hex ff, binary 101, char A
any value: { 1, 2, 3 }

The common specifiers are:

Specifier Meaning
{} default format for the type (strings need )
string (a slice of bytes)
decimal number
{d:.2} decimal with 2 digits after the point
/ hexadecimal lowercase / uppercase
binary
a single character
debug view of any value
{*} pointer address

The compiler checks the format string against the tuple at compile time. Mismatched counts or types are compile errors, not runtime surprises. The .{ a, b } syntax is an anonymous tuple: a struct with no field names, built on the spot.

std.debug.print writes to standard error, not standard output, and it ignores errors. It is meant for debugging and learning. For real program output you write to standard output, shown next.

Writing to standard output

In Zig 0.15 and later, standard output goes through a writer with an explicit buffer that you flush:

ZIG
const std = @import("std");

pub fn main() !void {
    var buffer: [1024]u8 = undefined;
    var stdout_writer = std.fs.File.stdout().writer(&buffer);
    const stdout = &stdout_writer.interface;

    try stdout.print("Hello, {s}!\n", .{"stdout"});
    try stdout.flush();
}

Three new things appear:

  • !void as the return type means "either void or an error". Writing can fail, so main must be allowed to fail. Error handling has its own lessons later.
  • try runs a call that may fail and returns the error from the current function if it does.
  • var buffer: [1024]u8 = undefined; is a 1024-byte array with no initial value. The writer fills it before sending bytes to the OS, which is why you need flush() at the end. Forgetting the flush means output can be lost.

Older tutorials write std.io.getStdOut().writer(). That API was removed in 0.15 when the I/O interface was reworked. If an example fails with "no member named getStdOut", this is the reason.

Common beginner errors

The compiler's messages are good. Three you will meet immediately:

  • Unused variable or constant: error: unused local constant. Zig refuses to compile code with names that are never used. Write _ = name; to discard on purpose, or delete the name.
  • Missing tuple: std.debug.print("hi\n") fails because the argument count does not match; add , .{}.
  • Strings with {}: printing a string with a plain {} fails because a byte slice could be text or numbers. Use .

A stand-in you can run

Zig's print checks the format against the values at compile time. C's printf does too, if you turn warnings on. This stand-in prints the same kinds of values as the placeholder example above.

C Stand-in (C): the same output as the Zig example

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Rust Stand-in (Rust): placeholders with names and widths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @import("std") return?

    @import returns a struct-like value; const std = @import("std") names it.
  2. 2. Why does std.debug.print("hi\n") fail to compile?

    Pass .{} when there is nothing to format.
  3. 3. Which specifier prints a string slice?

    prints bytes as text; is for numbers and for a single character.
  4. 4. What happens if you forget flush() on a buffered stdout writer?

    The writer collects bytes in your buffer and only sends them to the OS on flush or when full.
  5. 5. Where does std.debug.print write?

    It prints to stderr and ignores errors, which makes it handy for debugging.

Summary

  • @import("std") gives you the standard library; pub fn main() is the entry point.
  • std.debug.print(fmt, .{ values }) formats with placeholders like , and {d:.2}, checked at compile time.
  • std.debug.print writes to stderr; use a buffered writer and flush() for real output (0.15+).
  • Unused names are compile errors; discard them with _ = name;.

Next: Program Structure and Imports