Zook, a book for the Zig programming language
This book is intended to be a gentle introduction to the Zig programming language.
What is Zig?
Quoting from the official website -
Zig is a general-purpose programming language and toolchain for maintaining robust, optimal and reusable software.
Some of its features are -
- No hidden control flow
- No hidden memory allocations
- No preprocessor, no macros
It takes a novel approach to compile time metaprogramming through comptime which allows us write code that runs at compile time in virtually the same way as regular code.
It also acts toolchain for compiling C/C++ projects. The Zig executable allows us to compile existing codebases without changing anything.
License
© Crispy Strawberry. All rights reserved.
No part of this book may be copied in any format
without written permission of the author.
All code samples taken from other projects are owned
by their respective copyright owners.
The code samples owned by me in this book are licensed
under
CC0 1.0 Universal license.
Credits
All the credit goes to me and myself.
Personal Notes
According to someone, zook
means arse in morrocan.
I have not independently verified this claim but
left it as an exercise to the reader.
Installing
This page shows how to install the Zig language and have an environment which allows you to easily experiment.
Linux
-
Go to the download page
-
Scroll down to the Linux section inside master
-
Download the binary for your computer architecture. For example, if you have a x86-64 CPU, download the file named zig-linux-x86_64-[version].tar.xz
-
Extract it and put it in a suitable place.
-
Add it to PATH
-
Open a terminal. Run
zig zen
If you get something like
* Communicate intent precisely.
* Edge cases matter.
* Favor reading code over writing code.
* Only one obvious way to do things.
* Runtime crashes are better than bugs.
* Compile errors are better than runtime crashes.
* Incremental improvements.
...
Congratulations 😀. You have successfully installed zig 🎉🎉. Now go to the section to create a zig project.
Windows
-
Go to the download page
-
Scroll down to the Windows section inside master
-
Download the binary for your computer architecture. For example, if you have a x86-64 CPU, download the file named zig-windows-x86_64-[version].zip
-
Extract it and put it in a suitable place.
-
Add it to PATH
-
Open a terminal. Run
zig zen
If you get something like
* Communicate intent precisely.
* Edge cases matter.
* Favor reading code over writing code.
* Only one obvious way to do things.
* Runtime crashes are better than bugs.
* Compile errors are better than runtime crashes.
* Incremental improvements.
...
Congratulations 😀. You have successfully installed zig 🎉🎉. Now go to the next section to create a zig project.
macOS
-
Go to the download page
-
Scroll down to the macOS section inside master
-
Download the binary for your computer architecture. For example, if you have an Apple Silicon, download the file named zig-macos-aarch64-[version].tar.xz
-
Extract it and put it in a suitable place.
-
Add it to PATH
-
Open a terminal. Run
zig zen
If you get something like
* Communicate intent precisely.
* Edge cases matter.
* Favor reading code over writing code.
* Only one obvious way to do things.
* Runtime crashes are better than bugs.
* Compile errors are better than runtime crashes.
* Incremental improvements.
...
Congratulations 😀. You have successfully installed zig 🎉🎉. Now go to the next section to create a zig project.
Basic Zig Project
Now that you have got zig up and running, it's time to start a basic project in zig.
-
Create a new directory where you want to put the new project.
mkdir my-zig-project && cd my-zig-project
-
Initialize a zig project in the current directory
zig init-exe
If you see something like
info: Created build.zig info: Created src\main.zig info: Next, try `zig build --help` or `zig build run`
then you have successfuly created a zig project. If not, then go through the installation section to check if you made any mistakes.
-
Open the folder in a text editor.
You should see a folder calledsrc
. This is where source code of your project lives.const std = @import("std"); pub fn main() !void { // Prints to stderr (it's a shortcut based on `std.io.getStdErr()`) std.debug.print("All your {s} are belong to us.\n", .{"codebase"}); // stdout is for the actual output of your application, for example if you // are implementing gzip, then only the compressed bytes should be sent to // stdout, not any debugging messages. const stdout_file = std.io.getStdOut().writer(); var bw = std.io.bufferedWriter(stdout_file); const stdout = bw.writer(); try stdout.print("Run `zig build test` to run the tests.\n", .{}); try bw.flush(); // don't forget to flush! } test "simple test" { var list = std.ArrayList(i32).init(std.testing.allocator); defer list.deinit(); // try commenting this out and see if zig detects the memory leak! try list.append(42); try std.testing.expectEqual(@as(i32, 42), list.pop()); }
For now, remove everything from
test "simple test" {
Now, lets go step by step throught the file.
main.zig
-
The first line in
main.zig
is#![allow(unused)] fn main() { const std = @import("std"); }
const
is used to declare constant namedstd
.
@import("std")
tells the zig compiler that we want to import the The Zig Standard Library is needed for things like printing to stdout, opening files, networking etc. -
pub fn main() void {}
is used to declare a function.
Thefn
keyword declares a function and main is the name of the function.
The return type comes aftermain()
. Here, the return type isvoid
.void
basicaly means we don't have anything to return.
main
is a special function that is excuted when the executable is run. It is the entry point of the executable.
Variables
What are variables?
They can be said to be places in memory where the data of your program is stored.
Variables in Zig
In Zig, variables are declared using the const
or var
keywords.
Immutable
Variables whose value cannot change are declared using the const
keyword.
They are immutable.
pub fn main() void { const age = 23; // Just ignore this for now _ = age; }
If you try reassigning a const variable, the zig compiler will throw an error.
pub fn main() void { const year = 2023; year = 2023; // ^^^^ This will fail as you try to change the value of a constant }
Mutable
Variables whose value can change are declared using the var
keyword.
The are mutable and their value can change.
pub fn main() void { // Here, we specify the data type of the year var year: i32 = 2023; year = 2024; // ^^^^ year is a var, so its value can change. }
General
By default, zig throws an error if a variable is declared
but it is not used. That is why we used
_ = age
in the first example as we don't use it.
All variables have a data type. It can be explicitly set
by adding : <datatype>
after the variable name.
pub fn main() { const x: u32 = 45; // ^^^^^^^^^^^^ x is constant which type is // an unsigned integer whose size is 32 bits. }