Zig's new LinkedList API (it's time to learn fieldParentPtr)
Published on: 2025-04-30 11:06:33
Zig's new LinkedList API (it's time to learn @fieldParentPtr)
In a recent, post-Zig 0.14 commit, Zig's SinglyLinkedList and DoublyLinkedList saw significant changes.
The previous version was a generic and, with all the methods removed, looked like:
pub fn SinglyLinkedList ( comptime T : type ) type { return struct { first : ? * Node = null , pub const Node = struct { next : ? * Node = null , data : T , } ; } ; }
The new version isn't generic. Rather, you embed the linked list node with your data. This is known as an intrusive linked list and tends to perform better and require fewer allocations. Except in trivial examples, the data that we store in a linked list is typically stored on the heap. Because an intrusive linked list has the linked list node embedded in the data, it doesn't need its own allocation. Before we jump into an example, this is what the new structure looks like, again, with all methods removed:
pub const SinglyLinkedList = struct { first : ? * Node = null , pub
... Read full article.