When dealing with optional fields, feature-gated behavior, or value-or-valueFrom unions, nil safety must be structural—not dependent on caller ordering or duplicated guards.
Standard rules
Value OR ValueFrom, treat the other side as potentially nil.Value is nil before dereferencing, or use a nil-safe deref helper.if obj != nil before calling methods, or make the method explicitly nil-safe.omitempty when appropriate to avoid emitting null.Example patterns
// 1) Constructor: initialize before early return
acc := &cpuAccumulator{
logger: logger,
topo: topo,
details: topo.CPUDetails.KeepOnly(availableCPUs),
result: cpuset.New(),
resultDetails: topology.CPUDetails{},
// init everything methods might rely on
numaOrSocketsFirst: ...,
availableCPUSorter: ...,
}
if numCPUs == currentlyAllocatedCPUs.Size() {
acc.take(currentlyAllocatedCPUs.Clone())
return acc
}
// 2) Union: never deref c.Value unless ValueFrom is absent
if c.ValueFrom != nil {
// handle/skip/filter; do not deref c.Value
} else if c.Value != nil {
quantity := c.Value.DeepCopy()
// 3) Feature-gated nil receiver
if f.batch != nil {
f.batch.SetDisabled(true)
}
Applying these rules prevents panics and semantic drift caused by nil fields, feature-skewed objects, and ambiguous “zero vs unset” cases.