Skip to content

feature: zig equivalent of @fieldParentPtr() #95

Description

@pierrec

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
 // ...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions