Just had a case where I need to do pointer arithmetic, which is brittle and forces me to use a specific struct layout:
type Tree struct {
click ClickList
core treeCore
// ...
}
func openTreeNode(click *ClickList, i int) {
tree:= c.PtrAs[Tree](click)
t := c.PtrAdd(tree, c.Sizeof[ClickList]()) // *treeCore
// ...
}
In this case, Zig sidesteps this with the @fieldParentPtr() builtin, which I find elegant and is comptime safe: it checks the field actually exists and computes the offset for you.
func openTreeNode(click *ClickList, i int) {
// Give me the Tree pointer from the pointer of its click field
tree := c.FieldParentPtr[Tree](click, "click") // *Tree
t := &tree.core
// ...
}
Just had a case where I need to do pointer arithmetic, which is brittle and forces me to use a specific struct layout:
In this case, Zig sidesteps this with the @fieldParentPtr() builtin, which I find elegant and is comptime safe: it checks the field actually exists and computes the offset for you.