chapter two

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

2.1.1 Variables

2.1.2 Basic types

2.1.3 Functions

2.1.4 Back to modules

2.1.5 That’s it?

2.2 Pointing You in the Right Direction

2.2.1 Single-Item Pointers

2.2.2 Arrays

2.2.3 Slicing and dicing

2.2.4 Buffers and Undefined

2.2.5 I’ve been Stringing You Along

2.2.6 A few points to review

2.3 Structs

2.3.1 Structs are also namespaces

2.3.2 Methods, sort of

2.3.3 Struct initialization in the wild