Golang中集合相关的库
一切编程语言的底层结构都是数组,其它复杂数据结构如Map, Stack,Heap和Queue都是基于数组建立起来的。
Go语言主流工具库推荐(含常用数据结构实现)
以下是目前Go生态中最主流且活跃的工具库,包含队列、栈、优先级队列等常用数据结构的封装:
1. 标准库container
Go标准库中已经提供了部分基础数据结构:
import ("container/heap" // 优先级队列(堆)"container/list" // 双向链表(可作队列/栈)"container/ring" // 环形链表
)
使用示例
// 优先级队列(最小堆)
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {old := *hn := len(old)x := old[n-1]*h = old[0 : n-1]return x
}// 使用
h := &IntHeap{2, 1, 5}
heap.Init(h)
heap.Push(h, 3)
2. 第三方优秀库
(1) gods ★12k+
最全面的Go数据结构库,包含:
- 列表(List)
- 栈(Stack)
- 队列(Queue/Deque)
- 优先级队列(PriorityQueue)
- 集合(Set)
- 字典(Map)
- 树(Tree/BTree/AVLTree/RedBlackTree)
- 图(Graph)
import "github.com/emirpasic/gods/stacks/linkedliststack"stack := linkedliststack.New()
stack.Push(1)
stack.Push(2)
val, _ := stack.Pop() // 2
(2) go-datastructures ★7k+
来自Workiva的高性能数据结构库:
- 先进先出队列(FIFO Queue)
- 优先级队列(Priority Queue)
- 并发安全队列(ThreadSafeQueue)
- 布隆过滤器(Bloom Filter)
- 跳表(Skip List)
- 区间树(Interval Tree)
import "github.com/Workiva/go-datastructures/queue"q := queue.New(10)
q.Put("item")
item, _ := q.Get() // "item"
(3) golang-set ★3.5k+
专精集合操作:
- 线程安全集合
- 并集/交集/差集运算
- 支持泛型
import mapset "github.com/deckarep/golang-set/v2"set := mapset.NewSet[string]()
set.Add("apple")
set.Contains("apple") // true
(4) go-collections ★1k+
现代化泛型集合库:
- 链表(LinkedList)
- 字典(Dictionary)
- 堆(Heap)
- 栈(Stack)
- 队列(Queue)
- 不可变集合(Immutable)
import "github.com/samber/go-collections/stack"s := stack.NewStack[int]()
s.Push(42)
val := s.Pop() // 42
3. 并发安全数据结构
(1) concurrent-map ★3k+
import cmap "github.com/orcaman/concurrent-map/v2"m := cmap.New[string]()
m.Set("key", "value")
val, _ := m.Get("key") // "value"
(2) go-concurrent
提供并发控制原语:
- 限流器(Rate Limiter)
- 熔断器(Circuit Breaker)
- 工作池(Worker Pool)
4. 特殊数据结构
(1) roaring ★2k+
位图(Bitmap)高效实现
(2) hyperloglog ★800+
基数估计数据结构
选择建议
- 简单需求:优先使用标准库
container
- 全面数据结构:选择
gods
或go-datastructures
- 生产环境:考虑成熟度高的
gods
或go-datastructures
- 泛型支持:选择
go-collections
或标准库泛型实现 - 并发场景:使用
concurrent-map
等专门库
性能对比(仅供参考)
数据结构 | 标准库 | gods | go-datastructures |
---|---|---|---|
队列 | list | 快30% | 快50%(并发安全) |
堆 | heap | 相当 | 快20% |
集合 | 无 | 快 | 极快(位图实现) |
这些库都有良好的文档和活跃的社区支持,可以根据项目需求选择合适的工具库。