You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言中含空结构体的下划线字段“_”的作用是什么?

What's the purpose of the _ 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 to SomeType (like type 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 makes SomeType a 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{} ensures SomeType is never mistaken for a plain struct{}. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:58:25