一切編程語言的底層結構都是數組,其它復雜數據結構如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% |
集合 | 無 | 快 | 極快(位圖實現) |
這些庫都有良好的文檔和活躍的社區支持,可以根據項目需求選擇合適的工具庫。