Home >Backend Development >Golang >Why Use Underscore Empty Struct Fields for Keyed Initialization in Go?
Purpose of Underscore Empty Struct Fields
In Go, it's possible to define structs with a field named "_" containing an empty struct. This idiom enforces keyed field initialization, where every field must be explicitly named when creating an instance of the struct.
Code Example
type SomeType struct { Field1 string Field2 bool _ struct{} }
Keyed Field Initialization
With this empty struct field, the struct must be declared using keyed fields:
// ALLOWED: bar := SomeType{Field1: "hello", Field2: true} // COMPILE ERROR: foo := SomeType{"hello", true}
Benefits
This technique has several benefits:
The above is the detailed content of Why Use Underscore Empty Struct Fields for Keyed Initialization in Go?. For more information, please follow other related articles on the PHP Chinese website!