Hasty Briefsbeta

Bilingual

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

a year ago
  • #LinkedList
  • #Zig
  • #Programming
  • Zig's SinglyLinkedList and DoublyLinkedList have been updated to use intrusive linked lists, which embed the node within the data structure for better performance and fewer allocations.
  • The new SinglyLinkedList structure is simpler and does not directly reference the data it contains, requiring the use of @fieldParentPtr to access the parent data structure from a node.
  • An example demonstrates how to use the new API, including creating users with embedded nodes, prepending them to the list, and iterating through the list to print user data.
  • @fieldParentPtr is introduced as a builtin function to safely obtain the parent structure from a field pointer, leveraging the known offset of the field within the structure.
  • The post discusses the trade-offs of the new API, acknowledging the complexity introduced by @fieldParentPtr but recognizing its utility in solving certain problems efficiently.