2 A practical guide
This chapter covers
- How modules and source files make up a Zig program
- Basic data types you will often work with
- Common builtin functions
- Interacting with multiple data in memory using pointers, arrays, and slices
- Using structs as both namespaces and a way to package data together
2.1 The anatomy of a Zig program
Zig programs follow a structure that should be familiar to programmers of just about any imperative language. The programs have imports, declarations, and a main
function, with a nice kick of Zig flavor. Let’s start with listing 2.1.
Listing 2.1 A simple program
const std = @import("std"); // #1 pub fn main() void { // #2 const x: i32 = 42; // #3 std.debug.print("{}\n", .{x}); // #4 }
Which outputs:
$ zig run ch02/basic_structure.zig 42
We’ll make extensive use of Zig’s standard library (std) throughout the book. Until you decide to reimplement printing formatted text to the console from scratch, you’ll find it useful too. To use std, all we need to do is call the builtin named @import
with the name of the standard library’s module, "std"
. The module is then assigned to a constant so that we can use and reuse it however we want.
Builtin
Builtin functions are provided by the compiler and are available in all Zig code. They cover a variety of low-level tasks that can’t be implemented in ordinary Zig code. You can easily identify a builtin by the @
prefix (like @import
).