Zig's new LinkedList API (it's time to learn fieldParentPtr)

https://news.ycombinator.com/rss Hits: 18
Summary

Zig's new LinkedList API (it's time to learn @fieldParentPtr) Apr 10, 2025 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 const Node = struct { next: ?*Node = null, }; }; Much simpler, and, notice that this has no link or reference to any of our data. Here's a working example that shows how you'd use it: const std = @import("std"); const SinglyLinkedList = std.SinglyLinkedList; pub fn main() !void { var gpa: std.heap.DebugAllocator(.{}) = .init; const allocator = gpa.allocator(); var list: SinglyLinkedList = .{}; const user1 = try allocator.create(User); defer allocator.destroy(user1); user1.* = .{ .id = 1, .power = 9000, .node = .{}, }; list.prepend(&user1.node); const user2 = try allocator.create(User); defer allocator.destroy(user2); user2.* = .{ .id = 2, .power = 9001, .node = .{}, }; list.prepend(&user2.node); var node = list.first; while (node) |n| { std.debug.print("{any}\n", .{n}); node = n.next; } } const User = struct { id: i64, power: u32, node: SinglyLinkedList.Node, }; To run this code, you'll need a nightly release from within the last week. What do you think the output will be? You should see somethin...

First seen: 2025-04-14 11:03

Last seen: 2025-04-16 12:17