Skip to content

proposal: allow eliding "_" fields in unkeyed struct literals #71458

@dr2chase

Description

@dr2chase

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 add structs.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., __ or underscore) 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    LanguageChangeSuggested changes to the Go languageLanguageChangeReviewDiscussed by language change review committeeLanguageProposalIssues describing a requested change to the Go language specification.Proposal

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions