Go语言中含空结构体的下划线字段“_”的作用是什么?
_ struct{} field in a Go struct? Great question! That quirky _ struct{} field might seem useless at first glance, but it serves a few practical, type-safe purposes in Go code:
Block accidental type conversions
Imagine you have another struct with identical exported fields toSomeType(liketype OtherType struct{ Field1 string; Field2 bool }). Without the_ struct{}field, Go would let you convert values between these two types—even if they’re meant to represent completely different concepts. The anonymous empty struct makesSomeTypea distinct type that can’t be converted to or from structurally identical structs, preventing subtle bugs.Signal intent: this struct isn’t meant for comparison or map keys
Quick note: empty structs are comparable, so adding_ struct{}doesn’t technically make the whole struct uncomparable. But it’s a clear hint to other developers that this struct shouldn’t be used with==or as a map key. If you wanted strict uncomparability, you’d use a field like_ []byte(since slices are uncomparable), but this pattern is more about communicating intent than enforcing rules.Avoid confusion with empty structs
If your struct’s fields are all optional or could be zero-valued, the_ struct{}ensuresSomeTypeis never mistaken for a plainstruct{}. This eliminates edge cases where zero-valued instances might be accidentally handled as empty structs in your logic.No runtime overhead
Empty structs take up zero memory in Go, so adding this field doesn’t bloat your struct’s size or add any performance cost—it’s purely a compile-time safety measure.
Here’s a quick example showing the type conversion protection in action:
type SomeType struct { Field1 string Field2 bool _ struct{} } type OtherType struct { Field1 string Field2 bool } func main() { var s SomeType var o OtherType // This line will fail to compile: cannot convert o (type OtherType) to type SomeType // s = SomeType(o) }
内容的提问来源于stack exchange,提问作者Duncan Jones

