Back to course

Generics with Comptime

Full Course: Zig Programming From Zero to Hero

Generics in Zig

In Zig, generics are implemented by functions that return a type. This is possible because types are first-class values at comptime.

zig fn List(comptime T: type) type { return struct { items: []T, len: usize, }; }

const IntList = List(i32); var my_list = IntList{ .items = undefined, .len = 0 };

This approach is powerful and much simpler than C++ templates or Java generics.