Share E-Book

Systems Programming with Zig MEAP V01 (Garrison Hinson-Hasty) (z-library.sk, 1lib.sk, z-lib.sk)

Author

Technology
Language English

Zig delivers performance, reliability, and complex integration in systems programming in a simple, modern package. Zig hits the sweet spot for systems programming. This new programming language is high-performance, low-level, ultra-reliable, and perfectly suited for serious projects like writing libraries, daemons and shell utilities, and even operating systems and embedded code. Systems Programming with Zig shows you how to write quality, useful Zig applications without relying on libraries or frameworks-even if you’re new systems programming. In Systems Programming with Zig you’ll learn how to: Understand the Zig perspective on systems programming Write idiomatic Zig code Integrate Zig with C, systems libraries, and scripting languages Networking, interpreters, and graphics from the ground up Unlike UI-centric applications that form the public face of your software, systems programs like OS kernels, device drivers, and utilities interact directly with the hardware or operating system. In these low-level programs, performance and safety are paramount. Zig is a new programming language that builds on the legacy of C, C++, and even Rust to provide a high-productivity systems programming environment that does not rely on awkward libraries and frameworks.

Format PDF
Size 2.9 MB
5
Views
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
MEAP Edition Manning Early Access Program Systems Programming with Zig Simple and safe OS kernels, interpreters, and network services Version 1 Copyright 2026 Manning Publications For more information on this and other Manning titles go to manning.com. © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 3
Welcome Thanks for buying the MEAP for Systems Programming with Zig! If you know a little programming, and you want to see how Zig can help you write better software, you’ve found the right book. If you’re coming from a systems background— especially from C, C++, or Rust— rest assured that you’ll find yourself writing Zig like a pro before you know it. I guarantee you will come away from this book with a few new tricks. We’re going to take a nice long stroll around all of my favorite corners of systems programming: from the terminal to driving the web to building interpreters and even to the bizarre land of low-level graphics. Along the way, you’re going to see how Zig’s unique design decisions, informed by a strict set of values, will make your programs faster and more reliable and extensible than ever. If you have a deep-seated appreciation for computing— and more importantly, a love of learning, and a drive to understand the technological world as we know it— I wrote this book for you. I fell in love with Zig because I saw a community of deeply pragmatic people who love to code. And more than that, they have an undying dedication toward making programming both productive and enjoyable. I strive to be worthy of that community, and I have put all my effort into writing a book that represents these values. Please be sure to post any questions, comments, or suggestions you have about the book in the livebook discussion forum. Good luck! — garrisonhh (Garrison Hinson-Hasty) © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 4
brief contents PART 1: FROM ZERO TO ZIG 1 Zig’s big ideas 2 A practical guide 3 Allocators, data, and comptime PART 2: ZIG FOR HACKERS: SIMPLE, PRACTICAL, AND EXTENSIBLE PROJECTS 4 A simple, stupid web server 5 A CRUD API 6 A Chip8 interpreter 7 Zig glue 8 Shader heck PART 3: ZIG FOR DEVOTEES 9 Hello, friends! 10 Porting our interpreter 11 Shader heaven © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 5
1 Zig’s big ideas  This chapter covers Zig’s place in the established world of programming  The priorities of the Zig language and community  How Zig relates to other systems programming languages, especially C  What it’s like to program in Zig  Software projects where Zig excels  Zig is a language made for builders. It’s a new direction for systems programming that aims to combine the best ideas from the past with a sleek modern design. It will enable you to write reliable, maintainable code that relies on the bare minimum third-party dependencies and runs just about anywhere. You might be a builder too, especially if you see yourself in figure 1.1. 1 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 6
Figure 1.1 Some of the kinds of developers that could benefit from Zig New software is constantly being written, and a lot of it is presented as a "better" replacement for something that we already know works, and works well. Zig might be new, but it’s not a fork in the road. If you ever plan to write a native library, a data processing tool, a performant backend, an embedded operating system, or any other kind of technology where performance and reliability are key, learning Zig will enable you to go from zero to robust code quickly and painlessly. On the other hand, Zig is not about moving from point A to point B in the fastest way possible. It demands knowledge first, and requires careful planning. It is not the best language for new programmers to learn. It solves problems that are familiar to more experienced developers, in ways that are overkill for complete newbies to understand. Additionally, if you’re in a position where placing short-term results over long-term resiliency and code quality is a trade-off you often find yourself making, you’re likely to find Zig’s demands frustrating. Zig’s community aims to build a culture around a set of well-informed opinions about the nature of software development. By making it clear how to do things the Zig way, Zig software is performant, resilient, and simple to deploy. If you value simple, legible, and performant code, enjoy self-directed learning, seek depth of understanding over blind convenience, and respect the tools that built the foundations of modern computing, Zig is made for you. 1.1 How are we going to learn Zig? I’m writing this book for people like me, who learn by doing. I’m going to spend as little time as possible telling you what to do, and as much time as possible cramming in all of the juicy morsels of Zig I can pull from the far reaches of my brain. 2 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 7
We’re going to read and write a lot of code. More importantly, we’re going to dissect a lot of code. I will pull on every relevant thread until you, the reader, can explain every line back to me, down to the syscall. After that, I’ll provide ample opportunities for you to take the reins and start hacking. I’ve filled these pages with projects that demonstrate a variety of techniques for writing effective Zig in realistic contexts. This will include developing minimal-dependency web services with databases, embedding real-world C libraries, packaging Zig for scripting languages, and getting our hands dirty with hardware-accelerated graphics. These projects will provide a well-rounded tour of Zig for the self-motivated programmer. I aim to equip you to add Zig to your toolbox, and to know when, where, and why it’s the right tool for your project. Not only that, I hope to impart a simple idea that is at the core of Zig’s design: the quickest way to write useful, reliable software that serves users is to slow down and deeply learn how things really work. 1.1.1 Zig AI Some of you may be wondering: Why would I learn a new language like Zig when I can simply ask an AI to program for me? If this is a question in your mind coming into this book, I have some follow up questions for you: Do you enjoy the act of programming, and enjoy learning more about how to perfect your craft? Do you enjoy providing the best possible experience you can for users and other developers? Do you write software where performance and reliability are paramount? If your answer to all of these questions is a resounding “No”, you have a good point. You have little to gain from learning Zig. The kinds of design decisions Zig has made will not make sense to you. Others of you may be wondering: Will AI tools be helpful for writing Zig, and will we be learning about them in this book? Unfortunately, LLMs aren’t particularly good at doing systems programming regardless of the language. They have a much harder time with C++ than something like Python or JavaScript. I can speculate that some of this has to do with sample size, and some of it has to do with inherent qualities of systems programming. 3 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 8
Systems code demands a lot of systems knowledge. It demands a recognition of the tiniest, most subtle details and a strong intuition for the larger scale design of a program. LLMs aren’t great at these things, at least right now, and they aren’t accelerating towards getting good at them. Despite my best efforts, at the time of writing I have not found AI tools to be helpful in writing Zig programs. However, if you are interested and optimistic, I would challenge you to try it yourself. If you find something that works well, I would love to hear about it! 1.2 Zig is C’s collaborator, not C’s successor If you’ve heard of Zig before checking out this book, you’ve almost definitely seen it placed in contrast to C. Zig is often compared to languages like Go, Nim, D, or Odin that each have their own approach to making systems programming more friendly and modern than C. Zig is designed to fit seamlessly into existing C and C++ projects and to integrate cleanly with these foundational languages in new code. While Zig prioritizes the kinds of problems that C also solves well, Zig is not a true competitor. C represents decades of battle-tested systems code and programming experience, a cultural legacy that deserves respect in all of its imperfections. The Zig community looks upon C with affection. Since C was designed, we have learned more about programming language design. The standard for effective tooling has been raised. We’ve refined ideas about type systems, memory, and metaprogramming. Computers have changed, too - innovations like vector instructions, a switch from speeding up CPU cores to adding them, and the widespread implementation of CPU hardware caches means that writing optimized software looks very different in the 2020s than it did in the '90s. This new reality is at the core of Zig’s design priorities. Zig is a systems language built to shake off the past and embrace the present. Just as C has underpinned the last 50 years of technology, Zig is built to face the next 50 - with C right by its side. 1.2.1 Zig was born into a thriving ecosystem A problem that faces every new programming language is a lack of useful code already written in the language. Instead of relying on the Zig community alone to port or rewrite the vast software ecosystem, Zig programmers have inherited the C/C++ ecosystem. Zig can not only link to C and C\++, but Zig’s build system is also a complete build system for C and C++ – drop–in compatible with Clang, one of the most widely used C/C++ compilers. Zig code can even import C-compatible header files just like any C program. ZIG IS TRULY FLUENT IN C With modernized language features, it can even be easier to use C code from a Zig program than from a C program: 4 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 9
Null must be handled in Zig, and is baked into the type system with strong compiler checks. This prevents a class of C bugs which involve passing NULL to code that doesn’t expect it. Zig provides types and semantics to separate pointers to a single item and pointers to multiple items, as well as a built-in fat pointer type. Reusable build scripts allow libraries to be built from source using individualized configuration and static linking every time. Basically, this means optimized and reproducible programs right out of the gate. libc is bundled straight into the Zig compiler, so you don’t have to worry about version incompatibility. We’ll see even more examples of Zig’s excellent C integration throughout this book. If you’d like to see these capabilities in action, look no further than these three tools: The Zig compiler! Zig is built on top of LLVM and Clang, cornerstones of compiler infrastructure in 2025, and primarily C++ projects. Bun (https://github. com/oven- sh/bun), a Javascript and Typescript toolkit. built using Zig to wrangle a wealth of industrial-scale C/C++ dependencies like JavaScriptCore, Webkit and Tigerbeetle. Lightpanda (https://github. com/lightpanda- io/browser), a browser made for automation, built using Zig to manage the V8 Javascript runtime (used in the Chrome browser), among a number of other C/C++ libraries. 1.2.2 Zig’s inheritance It’s not a mistake that C has stuck around both culturally and as a potential language for new projects. Zig builds on some of C’s most beloved elements in a number of important ways: Syntax should not be a barrier to understanding. C’s depth through simplicity is one of its greatest strengths. Zig uses a minimalistic but familiar C-style syntax, with an even greater emphasis on legibility and eliminating implicit behavior. Your compiled binary should map closely to your code. C has been described as a "high-level assembly" for its clean translation to machine code, although this quality is diluted as hardware changes over time. Zig aims to emulate this property in the modern era of computation. The programmer should have the final say. C code has few guardrails. You are free to generate as many future hours of painful debugging as you wish, but if you learn to wield C’s power responsibly, you can also create ridiculously creative and blazingly fast code. Zig provides a wealth of safety features, but also gives you the power to turn off all of the checks when the situation demands. 5 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 10
1.2.3 Zig’s improvements on C and C++ The C and C++ communities face persistent problems with a lack of consensus around tooling and how programmers should interact with the language. Here are some of the glaring issues that Zig solves: One consistent code style to make collaboration easier. Zig provides a single, uniform code style using an unconfigurable formatter bundled into the compiler. This mandated style removes a barrier to common comprehension, encouraging an open and collaborative environment. Straightfoward build and deployment processes across multiple environments. There is no universal standard for building C and C++ code. Zig provides a full-featured general build system with world-class cross-platform support through LLVM and complete C and C++ compatibility through Clang. Zig builds self-contained binaries from source by default, preventing vast classes of bugs. Reliable code is a priority. Errors are one of the most well-featured elements in Zig’s design. Unique syntax and type system features combined with a low overhead implementation is a comfortable middle ground between lower-level error codes and higher-level constructions like exceptions. Undefined behavior is explicit. C and C++ allow you to write code that is completely unpredictable, but allows compilers to aggressively optimize in some cases. While it’s possible to invoke this so-called undefined behavior in Zig, you will have to go out of your way to convince the compiler to let you do so. Memory management is simple, flexible, and safe. Zig provides a variety of type system and standard library features to make manual memory management easy, explicit, and configurable. Safety checks and a rich set of pointer types make it harder than ever to actually do unsafe things with memory. 1.3 Leveling up developer experience, for the users At the end of the day, Zig’s first priority is making life better for end users. Software is only good when it serves the needs of its audience. As shown in figure 1.2, Zig’s language design starts from the core idea that end user experience should come first - and concludes that programmers should be given the best possible tools to provide it. 6 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 11
Figure 1.2 Some of the ways Zig contributes to better user experience Because systems programmers have been doing hard and meaningful work for decades on projects that make the world go 'round, maybe they know what they’re talking about. While tooling and programming language choices have remained conservative, ideas in the field have been refined through trial-and-error in real-world code. Throughout this process, high- level languages have continued to push the boundaries of what code and the tooling around it looks like, in the pursuit of intuitive and accessible software. I think of Zig as a delicious stew made up of the best of ideas from across the world of programming language design. Zig’s opinionated foundation does everything it can to unleash developers to write good software. 1.3.1 Hey, did you forget something? Some of the features I deeply miss in other languages are those most despised by Zig newbies — a set of rules that make you ask, "Why won’t it compile when it clearly knows what I mean?" The Zig compiler wants you to write good code, and it is happy to stop you in your tracks to accomplish that goal. I also found certain so-called features incredibly frustrating at first. However, my annoyance quickly turned into consideration, and then into better code. NO DEAD CODE Unused variables and parameters are not allowed in Zig, unless the code explicitly discards them. Valid Zig code cannot contain unused variable unless it also demonstrates that this was intentional. Valid Zig code also can’t discard variables that are, in fact, used. In a similar vein, the compiler prunes all of the dead code it can find. Zig allows you to explicitly tell the compiler when a condition is unreachable. You can even provide your own compilation errors to help you understand why a particular change might have activated a previously impossible code path. 7 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 12
These features allow you to encode your assumptions in a way that will provide instant feedback to your collaborators and your future self. Instead of silently introducing bugs, let the compiler tell you what’s wrong. IT SHOULD BE CONST Variables must never be more mutable than necessary. Zig variables can be declared as either const or var, where const variables cannot be re-assigned to a new value. If a const value is changed, it’s an error. If a var variable is never changed, it’s an error too. From the site of declaration, you know whether a variable can change. This property provides a giant hint in reading and debugging a piece of code. NOTE As an added benefit, const-heavy code happens to be incredibly compiler-friendly, which is one of the ways Zig code can beat idiomatic C code in performance. DON’T FORGET TO HANDLE THAT ERROR Errors and return values must be handled or explicitly discarded. This prevents a slew of frustrating bugs found in other languages, especially with error codes and exceptions - Zig simply will not allow you to ignore the error. Zig programs can also specify the entire set of errors that a function may produce, allowing the compiler to check your assumptions about the possible ways some code could fail. This feature not only prevents unexpected crashes but also vastly improves the experience of using an unfamiliar library. TYPES MUST BE EXPLICIT Type coercion must be unambiguous. Expressions in Zig, especially regarding numeric types, are extremely restrictive about what types are valid for operations with each other. This forces programmers to think about when and why they are coercing types between each other, and to think critically about what type would be the best fit for every piece of data. It also prevents giant classes of potential bugs allowed in a less strict type system, where type casting or coercion is either unexpected or mutates data in an unintended manner. AMBIGUITY IS TECHNICAL DEBT Zig’s static checks are all designed to force programmers to handle potential ambiguities before they turn into visible bugs your end users will bother you about. If you care about speed, these checks will never incur any runtime cost when you compile for release. Zig aims for a happy medium between rigorous correctness and total freedom. When you need the guardrails, you have them. When you have good reason to disengage them, you make it explicit. The Zig compiler is here to help you in every way it can, but never at the cost of getting things done. 8 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 13
1.3.2 Do it at comptime Quite a lot of code running in the wild wastes time: For users, by eating up CPU cycles only to recompute the same exact result. For programmers, when programming language limitations force them to write unnecessary boilerplate. For reviewers, by being too confusing, complex, or repetitive to properly evaluate. Metaprogramming works to save time in these ways and others. You may have encountered metaprogramming before in many forms. C, C++, and Rust have macros which rewrite code before it is parsed, although Rust’s macro syntax is significantly more polished. Rust and C++ provide rudimentary evaluation of constant functions and expressions. Generic functions and data structures can be achieved using C++ templates and Rust’s well-featured type system, although in both cases programmers often find themselves confounded by novel-length compiler errors. On the opposite end, interpreted languages like Lisp, Python, and Ruby provide methods to chop and dice code however to you’d like, providing fantastic expressivity and flexibility. The caveat, of course, is that everything happens at runtime. When the metaprogramming a language provides isn’t enough, programmers are forced to reach for ugly solutions. Chromium, the basis for Google Chrome and the world’s most widely used browser engine, uses Python scripts in a variety ways to generate C++ code when C++'s features simply aren’t enough. It is also legendary for being difficult to build. I’m not saying that these scripts are the sole reason for this, but this is a glaring example where the C++ language and its hodgepodge of viable build tools lack the flexible metaprogramming that programmers actually need. Zig’s comptime feature allows programmers an extraordinary amount of freedom to run almost arbitrary code at compile time. This is a true paradigm shift for metaprogramming in a low level statically and strongly typed systems programming language. Comptime fills in the same gaps as generics, macros, code generation scripts, and constant functions and expressions, and adds almost zero new syntax. The result is code that is both more optimized and more legible than it would be using the alternatives. 1.3.3 Memory is a resource Every byte of data ever touched by a program must be stored somewhere in order to be useful. Zig assumes that you, the programmer, understand where your data should be stored and how you want to manage its lifetime. This is just like C’s malloc and free paradigm, but with even more control by giving you access to the data structures managing your program’s memory. This approach comes with a lot of trade-offs, but ultimately maximizes control and explicitness compared to other common approaches, as spelled out in table 1.1. 9 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 14
Table 1.1 Memory allocation strategies Style Pros Cons Stop-the-World Garbage Collection Requires no planning, resulting in faster development cycles. Unpredictable pauses in program execution. Memory overhead due to tracking every allocation. Not cache-friendly by default. Potential for reference loops. Little control over memory, and may eventually create performance or memory usage issues that are incredibly hard to solve. Reference Counted Garbage Collection Requires no planning, resulting in faster development cycles. Consistent runtime characteristics (no pauses). Often multithreading friendly. Creates small overhead on every allocation. Not cache friendly by default. Potential for reference loops. Static Analysis (Rust, research languages) Compiler is able to guarantee that compiled code is largely memory safe. No direct performance overhead. Code must be designed carefully to avoid cases where the compiler can’t prove safety. Memory leaks are still possible. Lifetimes must be thought of on an individual object basis. C-style malloc and free Fine-grained control over every allocation. No performance overhead. Tedious management. No guardrails. It’s extremely easy to create memory leaks or reference invalid memory. Failure often isn’t handled in practice. 10 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 15
Zig’s Allocators The same benefits as C- style manual memory management. Explicit lifetimes. Guardrails in safe mode. Easily stackable and swappable allocation strategies to suit a code path’s needs. Allows code to recover gracefully from allocation failure. Requires testing for safety to be checked. Even the simplest code must explicitly define the allocator. Memory management is not a solved problem. Different approaches work best for different problems. Garbage collectors, for example, provide a lovely developer experience and speed of development at a cost to the runtime performance of an application. Zig provides a smooth and well-integrated method of manually managing memory, and allows developers to tweak and customize the way their data is managed to their hearts' content. When resources are tight or you want to squeeze every bit of speed out of your program, you’re going to want Zig’s fine level of control. 1.3.4 Building is not an afterthought Whether you’re a small-time hobbyist or a software architect with a storied career, doing the work of actually making your code run in a reproducible manner is unavoidably important if you plan to share it. Zig’s build scripts and declarative package management make it easy to do things the right way from the beginning: The Zig compiler never wastes your time. The Zig team puts an incredible level of effort into optimizing every possible piece of the compiler, with a performance-first, data-oriented style utilized from the very beginning. The creator of Zig, Andrew Kelley, discusses this in his 2021 talk on practical data-oriented design (https://vimeo. com/649009599), where he demonstrates a realistic approach to writing fast code for modern CPUs that doesn’t sacrifice legibility. As of that talk in 2021, the Zig compiler could generate intermediate code at a rate of 8.9 million lines of code per second on consumer hardware. Zig allows you to take the memory footprint of your programs right down to the nailbed, and crank every last bit of performance out of your CPU cores. NOTE I’m going to teach you how to apply some of those data-oriented principles, too! 11 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 16
HERMETICITY When given the same input, a hermetic build system is able to produce the same output in a reproducible and deterministic manner - regardless of what machine you’re building your code with. Hermetic by default. Zig is able to produce the same exact binary for the same platform regardless of where your project is compiled. For most use cases, if you use Zig’s package manager and the cross-platform standard library APIs, you will never have to make any code modifications to run your code on major platforms. When you’re releasing your code to end users, this also makes it easy to ship - simply compile your code for each target you wish to support, and the installation process can be as simple as a single download. Cross-platform doesn’t cost extra. Zig is able to compile your code for any supported platform, from any supported platform. Your binaries will be self-contained by default, making it trivial to distribute your code. Caching makes compile-and-run cycles stupid fast. Because Zig can rely on itself to produce the same results for its build targets, it is able to cache every step of your build process. This results in recompiling always taking the minimum time necessary. Reliable, secure and decentralized package management. Instead of managing a centralized package database, Zig just needs a URI for a tarball. If your dependencies live on popular git services like GitLab or GitHub, they are already available as a Zig package. Your packages will always be locked to the same source code hash until manually updated, guaranteeing that any change in the code you’re fetching is explicitly desired. Zig allows programmers to stop compromising. It’s a toolchain that understands and respects the complexities of building modern software, and takes every possible step to make that process as straightforward as possible. Zig will allow you to stop wasting time in dependency hell, configuring containers and learning a 13th build script language, and get back to writing useful code. 12 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 17
1.4 Learning Zig without frustration The problem with teaching the basics of Zig is that Zig is a carefully constructed, minimalistic language. On one hand, there are few syntax features to understand. There are no corners of the language that are too opaque and arcane to understand without a little time and know-how. On the other hand, if you haven’t yet been exposed to Zig’s unique style and techniques, you might find yourself frustrated at being unable to accomplish a task that’s so easy in a language you’re more used to. Additionally, Zig’s absolute dedication to explicitly specifying every bit of behavior is a double-edged sword for those new to the language. You simply must take responsibility for every statement and expression or else the compiler will figuratively cross its arms and pout. I’ll illustrate what I mean in figure 1.3. Figure 1.3 Zig’s learning curve, scientifically speaking. 13 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 18
I don’t mean to scare you away from Zig. What I mean to emphasize is that your understanding of Zig won’t click into place immediately — at certain points, you might want to fight the compiler (or the humble author). At least, this is my personal experience from reading programming books. We’ll revisit critical topics over and over throughout the book. If a concept isn’t clicking, I encourage you to move on and return to the material later, armed with more knowledge and a fresh perspective. 1.5 Just Don’t Get Stuck! It’s That Easy Here are some suggestions to help you avoid getting stuck and to get the most benefit out of your time with this book: 1.5.1 Read errors before you weep I’ve noticed that programmers moving from languages with fewer compiler checks and weaker type systems tend to get frustrated quickly with compiler errors. When you’re used to a more permissive language, it can feel like the code is being temperamental and argumentative. Although Zig’s error messages can be jargon-heavy, they’re designed to help you. They report exactly what they see, and often they will even provide accurate suggestions for a simple fix. Before you rage-quit, take a step back and see if you can identify what the error message is communicating. More often than not, once the code compiles, it works as you expected. 1.5.2 Use a debugger Debuggers are built with the purpose of allowing you to understand exactly what your code is doing with fine granularity — even if you know the code in question to be bug free. If you’re not sure what a particular line of code is doing, use a debugger to find out! Zig integrates nicely with lldb, gdb, and any other debugger that supports the standard DWARF debugging format. Your editor of choice is likely to have native debugging features or a way to plug into these fabulous pieces of technology. 1.5.3 Use zig fmt Zig has one single code formatter, included as the compiler subcommand zig fmt. In the short term, using zig fmt will make it easier to write code in a style that is consumable for other Zig programmers to read and help you with your code. It will also grant you the same benefits of other automatic code formatters in general. It will save you the annoyance of fixing formatting and reduce syntax mistakes, and its style consistency will allow you to spend more of your time thinking about how your code works rather than what it looks like. Once you spend some time with the common style under your belt, you will also notice that others' code is easier to read and debug. Over the course of your time with Zig, using the common formatter will only speed up your development cycle and remove a barrier to collaboration. 14 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 19
1.5.4 Explore, don’t copy This book has lots of code examples. I’m going to walk you through a problem and then demonstrate how I would solve it. Sometimes I write things in a particular way to help you avoid a pitfall that might not be immediately obvious or to introduce a concept. The code in this book is meant not to be a bible for you to follow but rather a vehicle for information — if you see something interesting on the side of the road, so to speak, I want you to look closer! GUESSING AND CHECKING Throughout the book, I provide jumping-off points with a "Guess and Check" annotation. GUESS AND CHECK What do you think about X? If you see one of these sidebars and you’re not absolutely confident that you know the answer, take a moment to guess what effect X will have and then check your understanding by doing X! With that out of the way, let’s get to programming: 1.6 How does Zig feel? If you’re still reading, I hope that you’re itching to know what it actually feels like to write Zig code. Let’s get right into it with baby’s first Zig program! 1.6.1 All Your Codebase “All your codebase are belong to us” is a reference to an early 2000s internet meme, in which the phrase “All your base are belong to us” appears in a poorly translated release of the game Zero Wing. Instead of writing the apocryphal ‘Hello, World!’ program, Zig programmers learn to print this phrase to a console instead. To anoint this book and the beginning of your storied Zig career, why don’t you try it out? 15 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
Page 20
ON ZIG VERSIONS AND OUR RUNTIME ENVIRONMENT Many programmers opt to use Zig’s bleeding-edge nightly builds. Unfortunately, this book can’t be updated nightly — so I’ve chosen to stick with Zig’s latest stable release at the time of writing. Currently, this means Zig 0.15.1. If you already have Zig installed, you can figure out what version it is with the zig version command. As far as using the console goes, I wrote this book primarily on Debian Linux using bash. However, if you are not a Linux nerd like me, don’t be deterred. The terminal commands I use should work on any major operating system: Windows, OS X, Linux, probably more. If operating system differences come up, I will mention and explain them. Let’s get started with listing 1.1. Save to a file like hello.zig, and run with zig run hello.zig! NOTE zig run will compile and execute Zig for simple one-off code like this. but writing a build script will vastly simplify your life for code that is truly useful. Listing 1.1 All your codebase belong to us #1 Import the standard library module. #2 Declare our main function which will run when we execute this code. This function has no return value, so we say that it returns void. #3 Use the debugging print function to print our message! std.debug is a namespace that contains helpful code for us to debug our programs, and print is a function within that namespace. Ignore the .{} syntax for now; we’ll get back to that later! // #1 const std = @import("std"); // #2 pub fn main() void { // #3 std.debug.print("All your codebase are belong to us!", .{}); } 16 © Manning Publications Co. To comment go to liveBook Licensed to Masiar Ighani <mighani@web.de>
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List