29

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?

6
  • 5
    Unkeyed literals means this: SomeType{"foo", true} as opposed to SomeType{Field1:"foo", Field2: true} the _ struct{} field prevents the former. Commented Jan 22, 2018 at 12:10
  • 3
    groups.google.com/forum/#!msg/Golang-Nuts/NSjVW82i0mY/… There is an exactly same question, but on golang-nuts. Commented Jan 22, 2018 at 12:13
  • Just try to create an unkeyed literal and you'll see. Commented Jan 22, 2018 at 12:13
  • I got the link by searching the code "ProgInfo". Hope this trick help you. Commented Jan 22, 2018 at 12:17
  • 4
    ... also please note that the prevention works only for client packages since the _ is unexported, while inside the package that defines the type you can still do SomeType{"foo", true, struct{}{}} Commented Jan 22, 2018 at 12:18

1 Answer 1

48

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.

Sign up to request clarification or add additional context in comments.

4 Comments

would you mind to explain what is "keyed" field now, and why do we need it?
@Nulik When you declare a struct with keyed fields, it looks like this: 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}.
Is there a reference in the official Go documentation for this?
Note: unkeyed literals can still be used in this case e.g. SomeType{"hello", true, struct{}{}} playground

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.