Ray's Knowledge Base
Unlock

Put mutually exclusive fields in a union, never grow a struct with variant-only fields

PreferenceVerified 29 Sep 2026Holds project: dftracer-utils
Preference. A rule, why it holds, and how to apply it.

Rule#

Put mutually exclusive fields into a union. Never grow a struct with fields that only one variant uses. Keep every union already made. Make the union as safe as C++ allows with factory functions that set the right member, such as window_spec, frame_spec, rate_spec and session_spec for dftu_window_spec.

Why#

The user wants the minimal memory footprint and accepts less safety for it, since this is C++ and not Rust. An agent argued that a union only pays off for structs held in large numbers, and that few short-lived structs such as a window spec do not need one. The user overruled this.

How to apply#

When a struct gains a field that only one use of the struct needs, key the variants by a function or kind enum and switch the field set to a union. Add one factory function per variant that sets the right member, and use only those factories at call sites. After all plans are finished, write a union and memory-layout spec for the project.

Evidence#

2026-09-30 session in dftracer-utils: the user corrected an agent that had kept per-function window params as plain struct fields; the params became one union keyed by func (C spec 72 to 56 bytes) with factory functions.

Also found by searching

  • adding a field only used by one variant of dftu_window_spec struct
  • should I add new fields to the struct or use a union for exclusive options
  • how should variant-specific fields be laid out in dftracer-utils C structs
  • union with factory functions window_spec frame_spec rate_spec instead of fat struct
  • struct keeps growing with fields only one variant uses, should I use union or separate struct?
  • agent argued a union is not worth it for a few short-lived structs; what is the house rule?
  • how should I structure mutually exclusive parameters in C++ structs like dftu_window_spec?
  • minimal memory footprint C++ tagged union with factory functions vs std::variant for spec structs