proposal: allow eliding "_" fields in unkeyed struct literals #71458
Labels
LanguageChange
Suggested changes to the Go language
LanguageChangeReview
Discussed by language change review committee
LanguageProposal
Issues describing a requested change to the Go language specification.
Proposal
Milestone
Proposal Details
Change treatment of
_
fields so that they may be omitted from unkeyed struct literals and (if omitted) do not count as unexported fields. In the case of a struct with multiple_
fields, either all must be present or all must be omitted, to avoid ambiguity.The reason for this is to make it easier to use
_
fields for things like establishing field alignment, modifying layout, and other type attributes. Without this change,_
fields require providing pointless initial "values" in unkeyed literals, and make it impossible to use unkeyed literals across package boundaries (it may be bad style, but it is legal Go and probably exists -- a particular use case is Windows). One specific motivation was looking at the work required and effects on code/tools/usability to addstructs.HostLayout
annotations to the code generated by cgo; it was messy and unpleasant.This breaks no Go code, so it is compatible.
It also "potentially affects" very little code anyway; unkeyed literals for structs with
_
fields are rare. I ran an ecosystem analysis of 44,000 Go projects that were imported 5 or more times. Of those, there were only 137 instances of an unkeyed literal "initializing" a_
field. Of that 137, 127 were in tests, of of that 127, 75 were literals for the same struct type. Of the 10 "non-test" examples, it turned out to really be only 5 because of duplication in the report, appearing in only 3 p[rojects, and 2 of that 3 involved VNC (i.e., derivative code).In any case where the export-forbidding properties of
_
were desirable, renaming that field to any other export-forbidding name (e.g.,__
orunderscore
) obtains the same effect.This will require a change to the Go compiler, and to tools that analyze Go code, so that both forms of struct literals are recognized.
The text was updated successfully, but these errors were encountered: