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?
A structure or struct in Golang is a user-defined type that allows to group/combine items of possibly different types into a single type. Any real-world entity which has some set of properties/fields can be represented as a struct.
What's an empty struct? An empty struct is a struct type without fields struct{} . The cool thing about an empty structure is that it occupies zero bytes of storage. You can find an accurate description about the actual mechanism inside the golang compiler in this post by Dave Chaney.
The empty struct is a struct type that has no fields.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With