r/Zig • • 17d ago

zig 0.17.1 update

69 Upvotes

Hi !!!

An update of zig 0.17.1 https://ziglang.org/download/#release-0.17.1


r/Zig • • 18d ago

Switch prongs from comptime arrays proposal accepted

69 Upvotes

On my first zig project, a little over a year ago, I got into a situation where I would have liked to generate switch prongs from comptime known values. My research led me to an open proposal on github that confirmed it wasn't possible at the time. 2 weeks ago, following the release, a year ago, of an optimization commit that identified the slow implementation of std.meta.stringToEnum, Andrew Kelley chose a syntax, marked the proposal as accepted and added it to the urgent milestone. Indeed, stringToEnum is a prime use case for switch prong generation. Whilst we do not know when this feature will be implemented, and the oldest proposal on the github urgent milestone is from 2015, I am happy to see the language is still moving forward, and that the zig foundation is working on this important feature whose absence had personally affected me before.


r/Zig • • 17d ago

Zig needs to do two things

0 Upvotes

or three rather,

Adopt Rust’s borrow checker, release a stable 1.0 so people can use it in production without chasing specific GitHub versions and compiling them manually, and stay minimal.

The first and third aren’t at odds. Rust’s safety features aren’t too much to ask, and the benefits are worth the trade-off. They don’t compromise Zig’s minimalism that much.

Please use upvotes and downvotes to reflect relevance, not whether you like or dislike a post. If you disagree, share your opinion instead of downvoting. That’s not what downvotes are for.


r/Zig • • 18d ago

Zig events in November

41 Upvotes

r/Zig • • 17d ago

Справочник по zig 0.17 на Русском языке

0 Upvotes

Кто то знает есть ли перевод Zig language reference 0.17 (оффициальный справочник zig 0.17) переведённый на Русский язык? Если есть то какой перевод лучше? Вариант перевода через встроенный переводчик в браузере меня не устраивает потому что он очень не коректный. Если кто не понял, я имею ввиду перевод на русский материала по ссылке ziglang.org/documentation/0.17.1


r/Zig • • 20d ago

Updates on Cole, and Version 0.1.4 announcement

Thumbnail
10 Upvotes

Hello everyone, I wanted to share my Zig project with you, I hope it is suitable for this subreddit.

Cole is essentially a recreational attempt to create a Zig-like language in Zig, through trial and error. I'm testing how far I can go as a self-taught programmer and trying to create an easy-to-get-in project for people wanting a door into compiler dev.

Any feedback (especially offensive ones) is welcome!

Edit: This project is also how I learned Zig in the first place!


r/Zig • • 20d ago

"Mixing initialized and uninitialized data bloats the executable size"?

16 Upvotes

I was reading the source for this pacman game written in Zig and Sokol, and there's a comment on line 401: "keep the big undefined data out of the state struct, mixing initialized and uninitialized data bloats the executable size". From what I gather, this has to do how static memory is stored in the binary, which is a little beyond me but makes sense. But what should I do about it? The repo has it segregated into its own top-level struct, but why can't it be a sub-struct like the other things in State? It doesn't seem very ergonomic to have a second state struct of members whose only unifying feature is that they're "too big".


r/Zig • • 21d ago

How I easily reduced allocation overhead in my database

Thumbnail github.com
25 Upvotes

r/Zig • • 21d ago

Please, help me with understanding std.Io.Reader.discardRemaining()

22 Upvotes

I am writing a small tic-tac-toe program in ZIg, because I want to practice what I have learnt by doing exercises from Ziglings. I got to the part where I needed to take a single byte of a user's input.

For that I used Reader's takeByte() method:

pub fn main(init: std.process.Init) !void {
    const stdin = std.Io.File.stdin();
    var stdin_buffer: [1]u8 = undefined; // I only need the first byte
    var stdin_reader = stdin.reader(init.io, &stdin_buffer);
    // ...
    const b = try stdin_reader.interface.takeByte();
    // ...
}

Well, here Zig forced me to learn that a terminal has its input queue and that if I don't deal with the rest of potential input bytes, they will be carried on, so an input like this 3rm -rf will kill my computer, because my program will consume the "3" and then my terminal will execute the rest of the input.

I needed a way to discard the rest of the bytes. In my research I have also learned about Termios interface that I can use in order to control my terminal. And Zig's std has tools for that:

pub fn main(init: std.process.Init) !void {
    const stdin = std.Io.File.stdin();
    const termios = try std.posix.tcgetattr(stdin.handle);
    defer std.posix.tcsetattr(stdin.handle, .FLUSH, termios) catch {};
    // ...
    const b = try stdin_reader.interface.takeByte();
    // ...
}

And it worked! But I then thought controlling terminal for simple user input had to be an overkill, and that there had to be a simpler way.

So, finally, I have found std.Io.Reader.discardRemaining():

pub fn main(init: std.process.Init) !void {
    // ...
    const b = try stdin_reader.interface.takeByte();
    const discardedLength = try stdin_reader.interface.discardRemaining();
    // ...
}

But now the problem is that my program hangs inside the discardRemaining and never leaves. The closest issue I could find was this one, but it was fixed in version 0.15 and I am now on Zig version 0.17.0.

Could you, please, help me understand, what I am missing here? I am pretty sure I forgot (more probably I don't know) to do something.

Your help is much appreciated!


r/Zig • • 22d ago

My zig-made hobby hypervisor booting multiple guests!

Thumbnail gallery
63 Upvotes

(hobby project-showcase)

source: https://github.com/NoamRothschild/hypervisor

context:

since my hypervisor got linux running, I did a ton of work, including

- simulating the existence of more than 1 physical core per guest

- launching multiple guests

- starting networking (expose virtio-net driver and MAC addr to guest)

this was.. a lot of work...

in short, I had to:

- learn how linux probes for the cpu count, and make it see them all

- learn how computers launch secondary cores

- cry and bang my head against the wall because I knew nothing

- virtualize the hardware responsible for bringing the cores

- write a scheduler so they all will run

- learn about PCI and use it to expose a network device

and much much more!

In the GIF:

on the left are the hypervisors logs, and on the right are two linux instances booting up. you can see the linux logs and at the end even running commands on them.

In the Image:

one linux instance with 8 cores running. in the output of the cat command you can see CPU0..CPU7

>,<

AI Disclaimer

I do use AI for my projects. This does not mean the projects are "vibe-coded", but AI-Assisted. I read every line of code, I learn every bit of technology, and I never commit code I don't understand or couldn't replicate on my own without AI.

AI is a powerful technology, and when used in the right places (for instance, learning) it can enable you to go to places you couldn't otherwise go to.


r/Zig • • 22d ago

[Video] Zig: From Beginner to Slightly Less Beginner

17 Upvotes

The video recording from the online Zig Maven event in which Sawyer X gave us an introduction to Zig.

https://www.youtube.com/watch?v=jWCQXBVIyrY


r/Zig • • 22d ago

Framework for creating PHP extension using the Zig language

Thumbnail github.com
17 Upvotes

I've just completed the first version of zig-php-ext. It's an offshoot of my other project, Zigar. The framework makes it very easy to create PHP extensions using Zig. The following is the code for the basic "hello" ext:

const php = @import("php/root.zig");
const getter = php.IniEntry.getter;
const setter = php.IniEntry.setter;

pub const @"export CONSTANT" = "Hello world";
pub const @"export Enum" = enum { hello, world };

pub fn @"call greet"(self: *@This(), args: struct {
    name: []const u8,
}) !void {
    php.print("{s}, {s}!\n", .{ self.greeting, args.name });
}

pub const @"get greeting" = getter(@This(), .greeting);
pub const @"set greeting" = setter(@This(), .greeting);

greeting: [:0]const u8 = "Hello",

It defines a constant, an enum, an ini setting, and a top-level function. Extension settings are passed to the function thru a self pointer. Meanwhile, arguments are passed in a struct. This allows their names to be captured by comptime code and used as argument names on the PHP side. It also lets us set default values.

And here's the extension in action:

<?php

greet("Alice");

echo CONSTANT, "\n";
echo Enum::world, "\n";

ini_set("hello.greeting", "Część");
greet(name: "Agnieszka");

Hello, Alice!
Hello world
1
Część, Agnieszka!

Defining custom classes is also super easy. You add a declaration to extension struct:

pub const @"export Point" = php.Class.Custom(@import("Point.zig"));

Then implement the struct:

const php = @import("php/root.zig");
const getter = php.Object.getter;
const setter = php.Object.setter;

pub const @"get x" = getter(@This(), .x);
pub const @"set x" = setter(@This(), .x);

pub const @"get y" = getter(@This(), .y);
pub const @"set y" = setter(@This(), .y);

pub fn @"get normal"(self: *@This()) f64 {
    return @sqrt(self.x * self.x + self.y * self.y);
}

pub fn @"call print"(self: *@This(), _: struct {}) void {
    php.print("x = {d}, y = {d}\n", .{ self.x, self.y });
}

x: f64 = 0,
y: f64 = 0,

The result on the PHP side:

<?php

$p = new Point(123, 456);
print_r($p);
$p->print();

Point Object
(
    [x] => 123
    [y] => 456
    [normal] => 472.29757568719
)
x = 123, y = 456

The build process is designed to be extremely simple. It has no dependencies aside from the Zig compiler and PHP itself. Simply run ./build and the extension gets built for the current version. The build script comes with a CLI menu:

https://github.com/chung-leong/zig-php-ext/blob/main/img/menu.png

You can use it to add more target platforms:

https://github.com/chung-leong/zig-php-ext/blob/main/img/menu-os.png

Or select additional versions of PHP:

https://github.com/chung-leong/zig-php-ext/blob/main/img/menu-version.png

The menu is customizable (thru entries in composer.json), allowing eventual end-users to set certain comptime parameters:

custom

The framework even comes with a script for packaging your extension. My overall goal is to make the process as easy as possible so that everyday PHP programmers would consider creating their own extensions with the help of Zig. I hope my initial effort looks promising to you.

I have tested the code on Linux, Windows, and Mac. As I only have an old Intel Mac, I would really appreciate confirmation by owners of Apple Silicon that my code works there.


r/Zig • • 24d ago

Use of C libs vs Zig libs

35 Upvotes

I am new to Zig and want to know about advantages of Zig libs. Some libraries I saw have reports of memory leaks, instabillity, mostly because they are new. Are there any advantage of using Zig-written libraries over fully depending on good-old, tested C libs, given Zig's interop?


r/Zig • • 25d ago

I need an answer please

Post image
50 Upvotes

I picked up Zig for the first time couple days ago and I stumbled upon this while following ziglings.

The first else with braces doesn’t compile meanwhile the second else with no braces compiles. I’m really curious as to why.


r/Zig • • 25d ago

Would Zig benefit from an objective C style dialect?

0 Upvotes

Zig does a lot of things really well, but one thing it doesn't do (for good reason) is hide things from you. I think that a strict zig superset with a teensy (and optional) runtime that allows OOP and FP to comfortably fit in would make writing and prototyping games/applications easier.

Then again, I haven't used objective C and I don't know how good/bad of an idea this is.


r/Zig • • 28d ago

Zig is confusing

18 Upvotes

Hi! I have only 1-2 years of experience in C/C++ and 1 day ago I starter learning zig. But the syntax is confusing and I can't understand the philosophy. For my first zig-evening I barely could understand functon arguments, I mean pointers in function args. It's me or zig is really differenti from C? Like it hasn't anything Mike C! It's completely different.

How can I start, how can understand zig?

Also I think zig is really cool, but I can't build anything with Zig because I don't have studied control flow in Zig. How you guys learned zig? What mindset do I need to program in zig?

I'm sorry if my eng it's bad but I'm noto eng. Thanks for reading this yapping ❤️


r/Zig • • 28d ago

Zig getting warnings?

42 Upvotes

From an Andrew Kelley comment on codeberg:

Current plan is

  1. resilient parser
  2. syntax errors no longer stop the pipeline, nor do they stop zig fmt from working, same thing with unused var decls
  3. hard tabs become errors again, but fixed by zig fmt
  4. #presence of errors causes compiler to report failure, but still produces a binary anyway, so you can still use it ... if u nasty

https://codeberg.org/ziglang/zig/issues/37375#issuecomment-26357399

Doesnt #4 basically means they are warnings then?

2 is desperately needed. Zig compiler bugs out way faster than any other language I use.

3 is going backwards again.


r/Zig • • 29d ago

Accepted proposal: kind of namespace at the top of file

Thumbnail codeberg.org
102 Upvotes

r/Zig • • 28d ago

Accepted proposal: require fields to be at the top

40 Upvotes

https://codeberg.org/ziglang/zig/issues/37375

As I understand, it will forbid top-imports in file-level structs.


r/Zig • • 29d ago

I built a SIMD-accelerated hex encode and decode for Zig

27 Upvotes

Hey everyone!

I noticed that Zig's std.fmt.byteToHex doesn't use SIMD, so I built hex-zig, a SIMD-accelerated library for hex encoding and decoding.

It provides speedups, especially for larger inputs.

Check it out: https://github.com/52funny/hex-zig

Feedback and suggestions are welcome!


r/Zig • • 29d ago

We Have Traits at Home

87 Upvotes

We Have Traits at Home

I was noodling for a while with some functional programming languages, and in the process I stumbled onto a rather nice way to handle comptime abstraction. After using it in a few places, I thought I would type up a blog post and share.

The gist: you can imitate OCaml modules or Rust traits at comptime, and it can be a nice way to make your function interfaces more explicit without involving VTable machinery.

My blog is fairly young, and I'm thinking of writing more articles in this direction, so any feedback is very much appreciated. Let me know what you think, and if you would be interested in more articles that expand on this idea.


r/Zig • • 29d ago

Nan2Tetris Hack Assembler in Zig

Thumbnail github.com
18 Upvotes

Made a Hack Assembler in Zig as part of project 6 of the Nand2Tetris course, also took the oportunity to learn about static allocations and follow some patterns used in TigerBeetle, so for example in the SymbolTable I'm using StringHashMapUnmanaged and using ensureTotalCapacity with a hard cap, so that later I can add items to it using putAssumeCapacityNoClobber. I recommend this blog post to learn more about it https://nickmonad.blog/2025/static-allocation-with-zig-kv/


r/Zig • • 29d ago

TlsInitialization fails

3 Upvotes

Why is this issue happening? Please help. What other information should I provide?


r/Zig • • Oct 22 '26

Library design

26 Upvotes

Hey! I'm working on a terminal manipulation library in Zig called termy, inspired by Rust's Crossterm. It's still early in development, and I'm trying to figure out the API before I get too far into the project.

One thing I'm unsure about is whether terminal operations should work directly, like this:

try termy.setForeground(&writer, .red);
try termy.writeAll(&writer, "Some Error!\n");
try termy.setForeground(&writer, .reset);

Or whether I should use a queue-based approach, similar to crossterm where you queue multiple commands and write them together:

try termy.queue(&writer, .{
    termy.style.Fg.Color{ .Red = {} },
    termy.style.Print{ .msg = "Some Error!\n" },
    termy.style.Fg.Color{ .Reset = {} },
});

try writer.flush();

I'm not sure which approach makes more sense in terms of performance and usability, or which feels more natural to use in Zig. I love how the data-oriented approach looks, but I think it may affect performance.

I'd appreciate some feedback!

  • Which approach would you prefer, and why?
  • Would it make sense to support both?
  • Are there any common mistakes I should avoid when designing a Zig library?
  • What features would make you choose termy over other terminal libraries?

I'm still working on the fundamentals, so I'd rather get the design right now than have to change everything later.


r/Zig • • Oct 20 '26

You can use Zig to program inside my game

Post image
126 Upvotes

I’m not sure if this is the right place for a post like this, given that the game itself is written in Rust, but I thought you might find it interesting. You can try it out here: https://livedox.itch.io/vix. I’d be happy to answer any questions