Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of a field named "_" (underscore) containing an empty struct?

Tags:

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?

like image 877
Duncan Jones Avatar asked Jan 22 '18 12:01

Duncan Jones


People also ask

What is _ struct {} in Golang?

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 is the use of empty struct in Golang?

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.

What does an empty struct mean?

The empty struct is a struct type that has no fields.


1 Answers

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.

like image 77
Duncan Jones Avatar answered Sep 24 '22 09:09

Duncan Jones