包含空结构的名为"_"(下划线)的字段的用途是什么?

Dun*_*nes 12 struct go

我已经看到使用这种模式的两段Go代码:

type SomeType struct{
  Field1 string
  Field2 bool
  _      struct{}    // <-- what is this?
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释这段代码完成了什么?

Dun*_*nes 12

声明结构时,此技术会强制使用键控字段.

例如,结构:

type SomeType struct {
  Field1 string
  Field2 bool
  _      struct{}
}
Run Code Online (Sandbox Code Playgroud)

只能使用键控字段声明:

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

// COMPILE ERROR:
foo := SomeType{"hello", true}
Run Code Online (Sandbox Code Playgroud)

这样做的一个原因是允许将来添加其他字段而不破坏现有代码.