3 Allocators, data, and comptime

 

This chapter covers

  • Interacting with files in a cross-platform manner
  • Thinking critically about memory management with Allocators
  • Making code reliable with errors and error sets
  • Loops, defer, and error-based control flow mechanisms
  • Using the Zig build system and comptime to customize compiled programs

We’re about to write cat. Over and over again, actually. You know cat, right? It’s a standard and ubiquitous program for shell scripting, made for concatenating files and commonly used to print file contents to the console.

I can hear you groan through the pages of this book: "Cat is so simple and straightforward, isn’t it? How could such a program even contain enough content to deserve a chapter in this otherwise excellent Zig book?"

Well, I’m interested in providing a grounded view on Zig and perhaps systems programming in general. The programs that underpin the world’s infrastructure, the programs you use every day without even a moment of consideration, the programs you couldn’t live without — these programs don’t need to be complex. They don’t need state-of-the-art algorithms or millions of lines of code. Useful code doesn’t need to be glamorous, it just needs to do the job you need in the way you expect.

3.1 Meow, says cat

3.1.1 Adopting our first cat

3.1.2 Allocating with Allocators

3.1.3 Errors, catch and try

3.1.4 Writers, Allocators and the interface pattern

3.2 Giving our cat more toys

3.2.1 For loops

3.2.2 While loops

3.3 Questioning our cat

3.3.1 All of the cat errors

3.3.2 Improvement can be a waste of time

3.3.3 Making our wheel nuclear grade

3.3.4 Writer, meet reader

3.4 Buffering and building with Buff and Bill

3.4.1 Why do we need build scripting?

3.4.2 Our build script

3.4.3 To buffer, or not to buffer

3.4.4 Say goodbye to our cats

3.5 Summary