News for hackers. Stuff that matters.
Re:Zig Performance Tracking Dashboard by hansvm on Monday December 06, 2021 @11:59AM (#29462295)
Zig makes it easy to write correct, reusable, low-level code.

Correctness: Zig (compared to C) introduced defer, errdefer, optional types, exhaustive switch statements, comptime, error sets, .... These have comparable succinctness to how error handling, null checking, macros and whatnot would be done in C, but they allow the compiler to check your work. Moreover, you gain some small optimizations because the compiler can infer intent a bit better (e.g., eliding null-checks on non-optional pointers).

Reusable: Zig operates on a principle of least power. If you don't need libc you don't link it. If you don't need an OS you don't depend on syscalls. If you don't need to use a specific memory allocator you pass one in as an argument. If you don't need a stack you don't set one up. Because of this, nearly the entire standard library can be used in UEFI apps, WASM modules, embedded unikernels, and all kinds of places where you'd be fighting against a typical C/C++/whatever toolchain.

Reusable: Comptime simplifies a lot of parts of the language design. It allows for easy generics (e.g., writing a maximum(a,b) macro in C that behaves correctly requires a ton of boilerplate or compiler-specific preprocessor extensions that don't even exist in any form in every major C compiler). It also allows you to write things like lookup tables and embedded data in Zig itself, rather than copy/paste/fat-fingering from another tool as part of your build process. Then those functions that generate your tables are testable and can be reused elsewhere.

Low-level: Much like C you have nearly complete control of the machine. You can easily override the _start symbol, drop into assembly, edit your favorite memory directly, set up dual stacks to trampoline your function calls against, call into any C library, present a C interface to Python, etc. Some low-level tasks like register bit-banging are way easier because the packed struct interface allows you to manipulate packed fields directly rather than shifting and masking your way to the right answer.

I'd reach for Zig any time I would have formerly reached for C, especially in any kind of atypical (embedded, no libc, no filesystem, ...) scenarios. I personally also don't find the high-level features of C++ and whatnot worth it compared to their downsides most of the time, so if I don't want something like Python/Perl/Javascript then I'm usually inclined to drop down as far as C (now Zig) anyway unless I have a good reason to do otherwise (like using the EGG library in Rust).

Is it worth checking out in 2021? Well, it hasn't hit 1.0, still has bugs, and isn't perfect. I'd be careful which production systems I ran on it. That said, I've had a blast using Zig for FUSE programs, Sudoku solvers, and all kinds of things. Give it a shot.

There are no comments on this comment yet.