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

荒凉一梦 提交于 2020-04-29 10:38:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!