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

I saw two pieces of Go code using this template:

type SomeType struct{ Field1 string Field2 bool _ struct{} // <-- what is this? } 

Can anyone explain what this code is doing?

+5
source share
1 answer

This method applies key fields when declaring a structure.

For example, struct:

 type SomeType struct { Field1 string Field2 bool _ struct{} } 

can only be declared using key fields:

 // ALLOWED: bar := SomeType{Field1: "hello", Field2: "true"} // COMPILE ERROR: foo := SomeType{"hello", true} 

One reason for this is to include additional fields in the structure in the future without breaking existing code.

+5
source

Source: https://habr.com/ru/post/1274862/


All Articles