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

后端 未结 1 1362
慢半拍i
慢半拍i 2021-01-01 14:22

I\'ve seen two pieces of Go code using this pattern:

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


        
1条回答
  •  生来不讨喜
    2021-01-01 15:09

    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.

    0 讨论(0)
提交回复
热议问题