Why the golang underscore struct field exists

Paul Yeo
1 min readJun 6, 2021

Chances are if you’ve written some go or delved into a well-maintained go project, you’ve seen structs with an underscore field:

type ListTablesInput struct {
_ struct{} `type:"structure"`
ExclusiveStartTableName *string `min:"3" type:"string" Limit *int64 `min:"1" type:"integer"`
}

> https://github.com/aws/aws-sdk-go/blob/7e0246814d8eb87bdc6850c44e8f75f020db80eb/service/dynamodb/api.go#L15104-L15115

The purpose behind using the _ field on a struct is to enforce keyed fields when initializing a struct.

input := ListTablesInput{
ExclusiveStartTableName: "table-name",
Limit: 100,
}
// instead of
input := ListTablesInput{"table-name", 100}

If you attempt to initialize a struct without the field names, you will get an error along the lines of `cannot use as type struct {} in field value`.

The big advantage of enforcing this rule when initializing structs is that any new fields added to the struct will not introduce a breaking changes. Say for example a new field were added like:

type ListTablesInput struct {
_ struct{} `type:"structure"`
ExclusiveStartTableName *string `min:"3" type:"string"` Limit *int64 `min:"1" type:"integer"` // New field
Option string
}

then from our previous examples, the struct initialization without the key fields would not compile because it now requires the new field to be added.

// valid still
ListTablesInput{
ExclusiveStartTableName: "table-name",
Limit: 100,
}
// fails to compile
ListTablesInput{"table-name", 100}

--

--