Go语言技巧:利用空结构体实现高效集合
在Go开发中,集合(Set)是常用的数据结构,但Go标准库并未直接提供。本文将介绍一个优雅的技巧——利用空结构体struct{}来实现高性能集合。
为什么选择空结构体?
空结构体在Go中占据零字节内存。当我们用map[string]struct{}表示集合时,每个键只占用键本身的内存,值不占用额外空间。相比之下,map[string]bool每个键还要额外存储一个布尔值。
基础实现
type Set map[string]struct{
}
func NewSet(items ...string) Set {
s := make(Set)
for _, item := range items {
s.Add(item)
}
return s
}
func (s Set) Add(item string) {
s[item] = struct{
}{
}
}
func (s Set) Contains(item string) bool {
_, ok := s[item]
return ok
}
func (s Set) Remove(item string) {
delete(s, item)
}
并发安全版本
若需并发使用,可结合sync.RWMutex:
type SafeSet struct {
m map[string]struct{
}
mu sync.RWMutex
}
性能对比
基准测试显示,map[string]struct{}相比map[string]bool在内存分配上减少约33%,GC压力也明显降低。
扩展技巧
泛型版本(Go 1.18+):
type Set[T comparable] map[T]struct{
}
这个轻量级实现既保持了代码简洁,又获得了最佳性能,是Go语言中“少即是多”哲学的典型体现。