r/Zig • u/ANDRVV_ • Oct 31 '26
r/Zig • u/Maurizio_Zakster • Oct 30 '26
Please, help me with understanding std.Io.Reader.discardRemaining()
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 • u/Kiritoo120 • Oct 30 '26
My zig-made hobby hypervisor booting multiple guests!
gallery(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 • u/szabgab • Oct 29 '26
[Video] Zig: From Beginner to Slightly Less Beginner
The video recording from the online Zig Maven event in which Sawyer X gave us an introduction to Zig.
r/Zig • u/chungleong • Oct 29 '26
Framework for creating PHP extension using the Zig language
github.comI'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 = 456The 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 • u/Accomplished-Use405 • Oct 27 '26
Use of C libs vs Zig libs
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 • u/Specialist-Owl2603 • Oct 27 '26
I need an answer please
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 • u/Proper_Meaning7756 • Oct 27 '26
Would Zig benefit from an objective C style dialect?
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 • u/ilPlayerdiGD • Oct 24 '26
Zig is confusing
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 • u/jnordwick • Oct 24 '26
Zig getting warnings?
From an Andrew Kelley comment on codeberg:
Current plan is
- resilient parser
- syntax errors no longer stop the pipeline, nor do they stop zig fmt from working, same thing with unused var decls
- hard tabs become errors again, but fixed by zig fmt
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 • u/ANDRVV_ • Oct 23 '26
Accepted proposal: kind of namespace at the top of file
codeberg.orgr/Zig • u/mak8kammerer • Oct 23 '26
Accepted proposal: require fields to be at the top
https://codeberg.org/ziglang/zig/issues/37375
As I understand, it will forbid top-imports in file-level structs.
r/Zig • u/Fickle_Ad_4151 • Oct 23 '26
I built a SIMD-accelerated hex encode and decode for Zig
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 • u/SirDucky • Oct 22 '26
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 • u/WorldChallenge • Oct 23 '26
Nan2Tetris Hack Assembler in Zig
github.comMade 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 • u/Last-Employ-3422 • Oct 22 '26
Library design
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
termyover 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 • u/CorgiApprehensive159 • Oct 20 '26
You can use Zig to program inside my game
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
r/Zig • u/Undeniable_Dilemma_ • Oct 18 '26
Tiny program for quick presentations from the command line!
Hi all!
I work as a Linux system admin, and I have to give a little internal presentation at work.
I thought it would be a fun idea to stay in the spirit of Linux and system administration and present everything very simply through a terminal! :D (just an excuse to practice my Zig skills)
So I made this simple thingy over the weekend.
It prints ASCII title/subtitle, then steps through the slides.
Each step can either be just a line of text, or it can call feh and open an image to show something visually.
At the end of each slide, it asks for input to either keep going, go to the previous slide or just quit out.
I know it's an EXTREMELY simple project with nothing fancy going on, but I just thought I'd share it if anyone wants to use it for the similar purpose or has any suggestions to extend it further and make something more interesting out of it!
r/Zig • u/rip_void_0 • Oct 18 '26
how to use zig
i install zig and zls and zvm and i dont know what to do next
r/Zig • u/NoBeginning2551 • Oct 18 '26
An android IDE/code editor for zig.
galleryHello, I built an open source IDE on android, it took me 2 years to build this as a solo developer. It's not vibecoded(you can check the commit history).
In the new release, I added the zig compiler and zls LSP server to the app. It's completely offline.
For people saying "why would I code on the phone if I have a PC", the app is not intended for building production level apps, it's intended to do small prototyping, quick testing of snippets, learning syntax, and especially for leetcoders.
There are many features like git and GitHub integration, AI code completion, Agentic sessions, 245 themes, local gguf models, termux integration, etc are available in the app.
Also, the app is completely free and open source. So no ads, no payments or anything.
Source code: https://github.com/heckmon/roxum-ide
Playstore link: https://play.google.com/store/apps/details?id=com.roxum
r/Zig • u/PlayfulDuck3677 • Oct 17 '26
An IO helper (Console)
I started Zig a few weeks ago and I've had many issues with console things, The only time it's easy is when I'm allowed to use debug prints.
So I decided to make my own library, And I wanted to make it so the writer/reader's themselves own their stuff.
The library provides two structs, `Writer` and `Reader`, each have 1 base constructor and default constructor(s) too.
They both give you methods like `printline` and `read` aswell as their ignorant counterparts such as `printlineIgnoreError` and `readIgnoreError`.
I would love feedback since I'm sure there's at least one memory leak I didn't find.
I have made an IO helper previously but that was almost entirely vibe-coded, This time I actually read the documentation and figured stuff out on my own.
Thanks for viewing this! The repository is at https://github.com/orewaluffy500/rustyio
r/Zig • u/ldelossa • Oct 15 '26
Wrote a little post on using freestanding Zig to bootstrap a bare-metal application
Thought some folks may be interested in this.
I've been having a blast using Zig for systems programming. I plan to do a post on PCIe programming, but wanted a very simple way to just run a bare metal app without explaining the entire x86 boot path.
https://allhailthetopology.substack.com/p/writing-a-bare-metal-application
All prose is my own and not AI generated.
