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
- Working 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
While some programming languages are designed for mathematical beauty, or to realize new and exciting ways to write programs, others are designed to maximize real-world pragmatism. Zig falls squarely in the pragmatic camp. This is an important reason the bulk of this book is about projects with real-world application.
I am a hands-on learner and I aim to cater to people who learn in a similar way. Regardless, to write cool programs we need to get the basics out of the way. I apologize, and you’re welcome!
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