问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/48381241/what-is-the-purpose-of-a-field-named-underscore-containing-an-empty-struct