freenode
Languages & Toolchains

Go sum types proposal weighs union syntax and safe access

A non-interface union design for closed variant sets is under active review, including soft-keyword experiments and type-inference trade-offs.

Go maintainers are advancing a proposal to add sum types as a dedicated non-interface union, aimed at closed sets of variants such as compass directions or protocol address families without falling back to interfaces or ad-hoc constants.

The design, refined by Ian Lance Taylor, frames the feature around a composite form provisionally called struct select. Variants would be selected and tested much like type assertions on interfaces. Safer comma-ok access is favored at the outset so that fetching the wrong variant does not panic; a looser form could be relaxed later if the two-result pattern proves too noisy in practice. Alternative spellings such as assertion-style syntax have also been floated to make the operation look less like ordinary field access.

Naming remains unsettled. Some prefer retaining familiar keywords so the construct feels native; others want a true union keyword. Robert Griesemer reported a limited experiment showing that union can be recognized where a type is expected while still accepting existing programs that use the word as an ordinary identifier, with language version deciding what the compiler ultimately accepts. That path would avoid a permanent awkward name in user code, though he stressed the jury is still out on the proposal itself.

Usability details are drawing equal scrutiny. One design goal is to let unions replace closed enumerations built from named constants, while leaving open string sets such as HTTP methods untouched. A separate concern is whether each variant should be its own type. If variant expressions carry distinct types, short variable declarations can infer a type that is too narrow, forcing explicit annotations on every reassignment between variants. Giving every construction the type of the whole union avoids that friction; users who need a distinct type can still wrap a named struct inside a variant.

Zero-value rules and the requirement that a union declare at least one variant are also on the table, because an empty union would leave the zero value undefined. The work sits in the long-running effort to give Go a first-class closed choice type without the open-ended dynamism of interfaces.