Image for post
Image for post

Is Zig the Long Awaited C Replacement?

Comparison with previous C contenders such as C++, D, Java, C#, Go, Rust and Swift

Image for post
Image for post

The Return of C’s Simplicity

Image for post
Image for post

Swift — The Language I Wanted to Love

Swift Syntax is Poorly Suited for Functional Programming

Where Zig Fits in the Programming Landscape?

Getting the Basics Right

Zig Memory Allocation

fn decimals(alloc: *Allocator, n: u32) !Array(u32) {
var x = n;
var digits = Array(u32).init(alloc);
errdefer digits.deinit();

while (x >= 10) {
try digits.append(x % 10);
x = x / 10;
}
try digits.append(x);
return digits;
}
errdefer digits.deinit();
const digits = try decimals(allocator, 4123);
defer digits.deinit();
for (digits.items) |digit| {
try print("{},", .{digit});
}

C Compatible

const c = @cImport({
@cDefine("_NO_CRT_STDIO_INLINE", "1");
@cInclude("stdio.h");
});

pub fn main() void {
_ = c.printf("hello\n");
}
export fn add(a: i32, b: i32) i32 {
return a + b;
}
#include <stdint.h>
int32_t add(int32_t a, int32_t b);

int main(int argc, char **argv) {
assert(add(42, 1337) == 1379);
return 0;
}
$ zig translate-c foobar.c

Minimalism

Simulating Generics in Zig

fn LinkedList(comptime T: type) type {
return struct {
pub const Node = struct {
prev: ?*Node = null,
next: ?*Node = null,
data: T,
};

first: ?*Node = null,
last: ?*Node = null,
len: usize = 0,
};
}
pub const Node = struct {
prev: ?*Node = null,
next: ?*Node = null,
data: T,
};
const PointList = LinkedList(Point);
var my_list = PointList{};
const p = Point{ .x = 0, .y = 2, .z = 8 };

var node = PointList.Node{ .data = p };
my_list.first = &node;
my_list.last = &node;
my_list.len = 1;

Simulating Interfaces in Zig

typedef struct _File {
void (*write)(void *fd, char *data);
void (*read)(void *fd, char *buffer, int size);
void (*close)(void *fd);
} File;

Final Remarks

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store