Zig for Rust Developers
Rust and Zig get compared a lot, and for good reason: both are modern systems languages, both have no garbage collector, and both want to replace a lot of C and C++. But they make very different bets. Rust puts a lot into the type system so the compiler can prove your program is memory safe. Zig keeps the language small and explicit and checks at runtime while you develop. If you know Rust, much of Zig will feel familiar, and a few things will feel like the safety net was taken away. This page goes through both, with the Rust and Zig versions side by side. The Rust examples were compiled with rustc 1.97 and the Zig ones with Zig 0.17.1.
The quick map
Section titled “The quick map”| In Rust | In Zig | Lesson |
|---|---|---|
Result<T, E>, ? |
Error unions E!T, try |
Zig Errors |
Option<T> |
Optionals ?T, orelse, if (x) |v| |
Zig Optionals |
Vec<T> |
std.ArrayList(T) + an allocator |
Zig ArrayList |
Box<T> |
gpa.create(T) / gpa.destroy(ptr) |
Zig Allocators |
Drop |
defer and errdefer, written by you |
Zig Defer |
Generics <T> |
comptime T: type parameters |
Zig Generic Functions |
| Traits | anytype (checked at compile time), tagged unions, vtables |
Zig Interfaces |
macro_rules!, derive |
comptime code and reflection |
Zig Comptime |
enum with data, match |
Tagged unions, switch |
Zig Tagged Unions |
&str, String |
[]const u8, []u8 you allocate |
Zig Strings |
Cargo, Cargo.toml |
zig build, build.zig + build.zig.zon |
Zig Build System |
unsafe |
No marker: everything is “trust me”, with runtime checks | Zig Illegal Behavior |
No borrow checker
Section titled “No borrow checker”This is the big one. Here’s a function that returns a reference to a string it created. Rust refuses it:
fn make_greeting(name: &str) -> &str { let greeting = format!("Hello, {name}!"); &greeting}
fn main() { println!("{}", make_greeting("Ada"));}error[E0515]: cannot return reference to local variable `greeting` --> main.rs:3:5 |3 | &greeting | ^^^^^^^^^ returns a reference to data owned by the current functionThe same mistake in Zig compiles:
const std = @import("std");
fn makeGreeting(name: []const u8) []const u8 { var buf: [32]u8 = undefined; return std.mem.print(&buf, "Hello, {s}!", .{name}) catch "?";}
pub fn main() void { const greeting = makeGreeting("Ada"); std.debug.print("{s}\n", .{greeting});}buf lives on makeGreeting’s stack, and the returned slice points into it after the function has returned. When we ran it, it printed junk bytes instead of Hello, Ada!, and different junk in different build modes. Zig does catch the most direct form (return &buf; is a compile error), but a slice of it gets through. No runtime check catches this one either.
So in Zig, you decide who owns memory and how long it lives, the way you would in C. The usual fixes are the ones you’d reach for in Rust anyway: let the caller pass in the buffer, or allocate and hand ownership to the caller:
const std = @import("std");
fn makeGreeting(gpa: std.mem.Allocator, name: []const u8) ![]u8 { return gpa.print("Hello, {s}!", .{name});}
pub fn main(init: std.process.Init) !void { const greeting = try makeGreeting(init.gpa, "Ada"); defer init.gpa.free(greeting); std.debug.print("{s}\n", .{greeting});}Output:
Hello, Ada!The return type ![]u8 (an owned, mutable slice) plus the allocator parameter tells the caller “you own this now, free it”. That’s a convention, documented in a comment, not something the compiler checks. Zig Ownership is all about these conventions.
What you get instead of compile-time proof:
- Runtime safety checks in
debugandsafebuilds: bounds, integer overflow, null unwraps, wrong union field. Many bugs that Rust rejects at compile time panic with a clear message in Zig. - Leak and double-free detection from the debug allocator and
std.testing.allocator. - No aliasing rules to satisfy: you can hold two mutable pointers to the same thing. That’s convenient for graphs, game entities and intrusive lists, and it’s also how data races happen. Threads need the same care as in C.
Whether that trade is worth it is the main question in Rust vs Zig. If you need memory safety proven, Zig is the wrong tool. If you want a language small enough to keep in your head, and you’re fine finding memory bugs with tests and checks, Zig is a nice place to be.
Ownership becomes allocators and defer
Section titled “Ownership becomes allocators and defer”Rust frees things for you when they go out of scope (Drop). Zig never runs code you didn’t write, so freeing is explicit, and defer puts the free right next to the allocation:
fn main() { let mut names = Vec::new(); names.push(String::from("Ada")); names.push(String::from("Linus")); println!("{} names: {:?}", names.len(), names);} // `names` and both strings are freed here, by DropOutput:
2 names: ["Ada", "Linus"]const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; var names: std.ArrayList([]const u8) = .empty; defer names.deinit(gpa);
try names.append(gpa, "Ada"); try names.append(gpa, "Linus"); std.debug.print("{d} names:", .{names.items.len}); for (names.items) |name| std.debug.print(" {s}", .{name}); std.debug.print("\n", .{});}Output:
2 names: Ada LinusThree differences to notice:
- Every call that might allocate takes the allocator (
append(gpa, ...)) and can fail witherror.OutOfMemory, so it needstry. Rust aborts on out-of-memory by default; Zig hands it to you as an error. "Ada"here is a string literal, so the list just stores a slice pointing at it. Nothing is copied. If you need owned copies, yougpa.dupe(u8, name)them and free them yourself.- There’s no move semantics. Assigning a struct copies its bytes; if it holds a pointer, both copies point at the same memory. Freeing through one of them is your responsibility, once.
Result becomes an error union
Section titled “Result becomes an error union”Error handling is where Zig and Rust are closest. ? is try, Result<T, E> is E!T, and match on the error is switch:
enum PortError { NotANumber, OutOfRange(u32),}
fn parse_port(text: &str) -> Result<u16, PortError> { let n: u32 = text.parse().map_err(|_| PortError::NotANumber)?; if n == 0 || n > 65535 { return Err(PortError::OutOfRange(n)); } Ok(n as u16)}
fn main() { for text in ["8080", "http", "70000"] { match parse_port(text) { Ok(port) => println!("{text}: port {port}"), Err(PortError::NotANumber) => println!("{text}: not a number"), Err(PortError::OutOfRange(n)) => println!("{text}: {n} is out of range"), } }}Output:
8080: port 8080http: not a number70000: 70000 is out of rangeconst std = @import("std");
const PortError = error{ NotANumber, OutOfRange };
fn parsePort(text: []const u8) PortError!u16 { const n = std.fmt.parseInt(u32, text, 10) catch return error.NotANumber; if (n == 0 or n > 65535) return error.OutOfRange; return @intCast(n);}
pub fn main() void { for ([_][]const u8{ "8080", "http", "70000" }) |text| { if (parsePort(text)) |port| { std.debug.print("{s}: port {d}\n", .{ text, port }); } else |err| switch (err) { error.NotANumber => std.debug.print("{s}: not a number\n", .{text}), error.OutOfRange => std.debug.print("{s}: out of range\n", .{text}), } }}Output:
8080: port 8080http: not a number70000: out of rangeThe difference: Zig errors carry no data. OutOfRange can’t hold the 70000. Errors are just names (small integers under the hood), which keeps them cheap and lets the compiler merge error sets automatically, but when you need details, you pass a “diagnostics” struct by pointer and fill it in before returning the error. Zig Custom Errors shows that pattern. In exchange you get error return traces: in debug builds, an unhandled error shows every try it passed through, without you adding context by hand.
Option<T> maps the same way: ?T, null, orelse for unwrap_or, and if (x) |v| for if let Some(v).
Traits and generics become comptime
Section titled “Traits and generics become comptime”Rust uses traits to say what a generic type must be able to do:
trait Shape { fn area(&self) -> f64;}
struct Square { side: f64,}
struct Circle { radius: f64,}
impl Shape for Square { fn area(&self) -> f64 { self.side * self.side }}
impl Shape for Circle { fn area(&self) -> f64 { 3.14159 * self.radius * self.radius }}
fn describe<T: Shape>(shape: &T) { println!("area: {:.2}", shape.area());}
fn main() { describe(&Square { side: 3.0 }); describe(&Circle { radius: 1.0 });}Output:
area: 9.00area: 3.14Zig has no traits. An anytype parameter accepts any type, and the function is compiled separately for each type it’s called with, like Rust’s monomorphization. If the type has what the code uses, it compiles:
const std = @import("std");
const Square = struct { side: f64,
pub fn area(self: Square) f64 { return self.side * self.side; }};
const Circle = struct { radius: f64,
pub fn area(self: Circle) f64 { return 3.14159 * self.radius * self.radius; }};
fn describe(shape: anytype) void { std.debug.print("area: {d:.2}\n", .{shape.area()});}
pub fn main() void { describe(Square{ .side = 3.0 }); describe(Circle{ .radius = 1.0 });}Output:
area: 9.00area: 3.14It’s duck typing, but at compile time. Pass something without an area method, like describe(42), and you get a compile error, though it points inside describe rather than at a missing impl:
main.zig:4:46: error: no field or member function named 'area' in 'comptime_int' std.debug.print("area: {d:.2}\n", .{shape.area()}); ~~~~~^~~~~There’s no declared contract to read, which is the main thing Rust developers miss. Good Zig code makes up for it with doc comments and, where it helps, a comptime check at the top of the function that gives a clear message. For runtime polymorphism (Rust’s dyn Trait), Zig uses tagged unions or a struct of function pointers, which is how std.mem.Allocator works. Zig Interfaces covers all three.
Rust’s macros mostly become comptime too: std.debug.print checks its format string while compiling, {any} prints most types without a derive(Debug), and Zig Reflection lets you loop over a struct’s fields the way a derive macro would.
No closures
Section titled “No closures”This surprises most Rust developers: Zig has no closures. A function can’t capture local variables. Where Rust passes a closure, Zig passes a plain function plus a context value:
const std = @import("std");
pub fn main() void { const word = "hello"; if (std.mem.findScalar(u8, word, 'l')) |i| { std.debug.print("first 'l' at {d}\n", .{i}); } else { std.debug.print("no 'l'\n", .{}); } const pos = std.mem.findScalar(u8, word, 'z') orelse 0; std.debug.print("'z' at {d} (0 if missing)\n", .{pos});
var scores = [_]i32{ 40, 95, 72 }; std.mem.sort(i32, &scores, {}, std.sort.desc(i32)); std.debug.print("{any}\n", .{scores});}Output:
first 'l' at 2'z' at 0 (0 if missing){ 95, 72, 40 }The Rust version would be word.find('l'), .unwrap_or(0) and scores.sort_by(|a, b| b.cmp(a)). In Zig, std.mem.sort takes a context (here {}, nothing) and a comparison function; std.sort.desc(i32) builds one for you. Iterator chains like .iter().filter().map().collect() become plain for loops. It’s more lines, and there’s nothing hidden in them.
Cargo becomes zig build
Section titled “Cargo becomes zig build”| Cargo | Zig |
|---|---|
cargo new app |
mkdir app && cd app && zig init |
cargo build |
zig build |
cargo run |
zig build run |
cargo test |
zig build test |
cargo fmt |
zig fmt . |
cargo add some-crate |
zig fetch --save <url of the package> |
Cargo.toml |
build.zig (a Zig program) + build.zig.zon (name, version, dependencies) |
--target after rustup target add |
-Dtarget=aarch64-linux, nothing to install |
The big difference is that build.zig is code, not configuration: you write Zig to describe steps, options and artifacts. There’s no central package registry like crates.io; dependencies are URLs (usually a Git repository or tarball) with a hash in build.zig.zon. There’s no official version manager like rustup either: you download a Zig release from ziglang.org, and each project should say which version it needs. See Zig Packages.
Things that will trip you up
Section titled “Things that will trip you up”- Unused variables and parameters are errors, not warnings. Use
_ = x;while you’re writing code. - Shadowing isn’t allowed.
let x = x.trim();has no Zig equivalent with the same name; pick a new one. constis the default you want; avarthat’s never changed is a compile error.- Strings are bytes.
[]const u8has no UTF-8 guarantee and no.chars().std.unicodehas the tools when you need code points. - Errors can’t be ignored, but values can’t be either: calling a function that returns something and dropping the result is a compile error. Write
_ = f();. - Zig isn’t 1.0. Rust’s stability promise doesn’t exist here yet. Expect to update code with each release.
Practice
Section titled “Practice”1. Port an Option function
Section titled “1. Port an Option function”Port this Rust function to Zig, using an optional return type:
fn first_even(nums: &[i32]) -> Option<i32> { for &n in nums { if n % 2 == 0 { return Some(n); } } None}
fn main() { println!("{:?}", first_even(&[3, 8, 5])); println!("{}", first_even(&[1, 3]).unwrap_or(-1));}Hint: the return type is ?i32. return n; and return null; replace Some(n) and None. Print an optional with {?d}.
Show solution
const std = @import("std");
fn firstEven(nums: []const i32) ?i32 { for (nums) |n| { if (@rem(n, 2) == 0) return n; } return null;}
pub fn main() void { std.debug.print("{?d}\n", .{firstEven(&.{ 3, 8, 5 })}); std.debug.print("{d}\n", .{firstEven(&.{ 1, 3 }) orelse -1});}Output:
8-1No wrapping needed: a plain i32 turns into ?i32 on its own. orelse is unwrap_or. Signed % on runtime values needs @rem (or @mod) in Zig, because the two differ for negative numbers and Zig makes you choose.
2. Port a closure
Section titled “2. Port a closure”In Rust, words.sort_by_key(|w| w.len()) sorts words by length. Do the same in Zig for "comptime", "zig", "allocator", "slice".
Hint: std.mem.sort([]const u8, &words, {}, lessThan) with fn lessThan(_: void, a: []const u8, b: []const u8) bool.
Show solution
const std = @import("std");
fn shorterFirst(_: void, a: []const u8, b: []const u8) bool { return a.len < b.len;}
pub fn main() void { var words = [_][]const u8{ "comptime", "zig", "allocator", "slice" }; std.mem.sort([]const u8, &words, {}, shorterFirst); for (words) |w| std.debug.print("{s} ", .{w}); std.debug.print("\n", .{});}Output:
zig slice comptime allocatorThe closure becomes a named function. If it needed to capture something, say a minimum length, you’d pass that as the context (the {} argument) and receive it as the first parameter instead of _: void.
- Zig has no borrow checker: lifetimes and ownership are conventions you keep, helped by runtime checks and leak detection.
- Allocators and
deferreplaceBox,Vec’s hidden allocation andDrop. - Error unions and
trywork likeResultand?, but errors are names without data. comptimeandanytypereplace generics, traits and most macros; checks happen when the code is compiled, without a declared contract.- No closures: pass a function and a context.
zig buildreplaces Cargo; there’s no central registry and norustup.
Next up: Zig for Go Developers, life without a garbage collector or goroutines.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Why Zig When There is Already C++, D, and Rust?: the Zig team’s own take on the differences.
- Zig language reference: comptime: how Zig does generic code without generics.
- Zig language reference: Errors: error sets, error unions and error return traces.
- The Rust Programming Language: Understanding Ownership: the Rust side of the comparison, if you want a refresher.