Tag Strucs

Golang Tips & Tricks #5 - blank identifier in structs
1 min read

While working with structures, there’s a possibility to initialize the structure without providing the keys of fields.

type SomeSturct struct {
  FirstField string
  SecondField bool
}

// ...

myStruct := SomeSturct{"", false}

If we want to force other (or even ourselfs) to explicitly providing the keys, we can add _ struct{} in the end of the structure.

type SomeSturct struct {
  FirstField string
  SecondField bool
  _ struct{}
}

// COMPILATION ERROR
myStruct := SomeSturct{"", false}

The code above will produce too few values in SomeSturct literal error. Try it yourself.