I've seen two pieces of Go code using this pattern:
type SomeType struct{ Field1 string Field2 bool _ struct{} // <-- what is this? } Can anyone explain what this code accomplishes?
This technique enforces keyed fields when declaring a struct.
For example, the struct:
type SomeType struct { Field1 string Field2 bool _ struct{} } can only be declared with keyed fields:
// ALLOWED: bar := SomeType{Field1: "hello", Field2: true} // COMPILE ERROR: foo := SomeType{"hello", true} One reason for doing this is to allow additional fields to be added to the struct in the future without breaking existing code.
SomeType{Field1: "hello", Field2: "true"}. The Field1 and Field2 are the keys. Unless you use the technique described in this Q&A, Go will let you omit the keys when declaring the struct: SomeType{"hello", true}.SomeType{"hello", true, struct{}{}} playground
SomeType{"foo", true}as opposed toSomeType{Field1:"foo", Field2: true}the_ struct{}field prevents the former._is unexported, while inside the package that defines the type you can still doSomeType{"foo", true, struct{}{}}