golang-data-structures

作者: samber

Golang 数据结构 — 切片(内部机制、容量增长、预分配、slices 包)、映射(内部机制、哈希桶、maps 包)、数组、container/list/heap/ring、strings.Builder 与 bytes.Buffer、泛型集合、指针(unsafe.Pointer、weak.Pointer)以及复制语义。适用于选择或优化 Go 数据结构、实现泛型容器、使用 container/ 包、unsafe 或 weak 指针,或对切片/映射内部机制有疑问时。

npx skills add https://github.com/samber/cc-skills-golang --skill golang-data-structures

Persona: You are a Go engineer who understands data structure internals. You choose the right structure for the job — not the most familiar one — by reasoning about memory layout, allocation cost, and access patterns.

Go Data Structures

Built-in and standard library data structures: internals, correct usage, and selection guidance.

  • For safety pitfalls (nil maps, append aliasing, defensive copies) see samber/cc-skills-golang@golang-safety skill.
  • For channels and sync primitives see samber/cc-skills-golang@golang-concurrency skill.
  • For string/byte/rune choice see samber/cc-skills-golang@golang-design-patterns skill.

Best Practices Summary

  1. Preallocate slices and maps with make(T, 0, n) / make(map[K]V, n) when size is known or estimable — avoids repeated growth copies and rehashing
  2. Arrays SHOULD be preferred over slices only for fixed, compile-time-known sizes (hash digests, IPv4 addresses, matrix dimensions)
  3. NEVER rely on slice capacity growth timing — the growth algorithm changed between Go versions and may change again; your code should not depend on when a new backing array is allocated
  4. Use container/heap for priority queues, container/list only when frequent middle insertions are needed, container/ring for fixed-size circular buffers
  5. strings.Builder MUST be preferred for building strings; bytes.Buffer MUST be preferred for bidirectional I/O (implements both io.Reader and io.Writer)
  6. Generic data structures SHOULD use the tightest constraint possible — comparable for keys, custom interfaces for ordering
  7. unsafe.Pointer MUST only follow the 6 valid conversion patterns from the Go spec — NEVER store in a uintptr variable across statements
  8. weak.Pointer[T] (Go 1.24+) SHOULD be used for caches and canonicalization maps to allow GC to reclaim entries

Slice Internals

A slice is a 3-word header: pointer, length, capacity. Multiple slices can share a backing array (→ see samber/cc-skills-golang@golang-safety for aliasing traps and the header diagram).

Capacity Growth

  • < 256 elements: capacity doubles
  • = 256 elements: grows by ~25% (newcap += (newcap + 3*256) / 4)

  • Each growth copies the entire backing array — O(n)

Preallocation

// Exact size known
users := make([]User, 0, len(ids))

// Approximate size known
results := make([]Result, 0, estimatedCount)

// Pre-grow before bulk append (Go 1.21+)
s = slices.Grow(s, additionalNeeded)

slices Package (Go 1.21+)

Key functions: Sort/SortFunc, BinarySearch, Contains, Compact, Grow. For Clone, Equal, DeleteFunc → see samber/cc-skills-golang@golang-safety skill.

Slice Internals Deep Dive — Full slices package reference, growth mechanics, len vs cap, header copying, backing array aliasing.

Map Internals

Maps are hash tables with 8-entry buckets and overflow chains. They are reference types — assigning a map copies the pointer, not the data.

Preallocation

m := make(map[string]*User, len(users)) // avoids rehashing during population

maps Package Quick Reference (Go 1.21+)

FunctionPurpose
Collect (1.23+)Build map from iterator
Insert (1.23+)Insert entries from iterator
All (1.23+)Iterator over all entries
Keys, ValuesIterators over keys/values

For Clone, Equal, sorted iteration → see samber/cc-skills-golang@golang-safety skill.

Map Internals Deep Dive — How Go maps store and hash data, bucket overflow chains, why maps never shrink (and what to do about it), comparing map performance to alternatives.

Arrays

Fixed-size, value types. Copied entirely on assignment. Use for compile-time-known sizes:

type Digest [32]byte           // fixed-size, value type
var grid [3][3]int             // multi-dimensional
cache := map[[2]int]Result{}   // arrays are comparable — usable as map keys

Prefer slices for everything else — arrays cannot grow and pass by value (expensive for large sizes).

container/ Standard Library

PackageData StructureBest For
container/listDoubly-linked listLRU caches, frequent middle insertion/removal
container/heapMin-heap (priority queue)Top-K, scheduling, Dijkstra
container/ringCircular bufferRolling windows, round-robin
bufioBuffered reader/writer/scannerEfficient I/O with small reads/writes

Container types use any (no type safety) — consider generic wrappers. Container Patterns, bufio, and Examples — When to use each container type, generic wrappers to add type safety, and bufio patterns for efficient I/O.

strings.Builder vs bytes.Buffer

Use strings.Builder for pure string concatenation (avoids copy on String()), bytes.Buffer when you need io.Reader or byte manipulation. Both support Grow(n). Details and comparison

Generic Collections (Go 1.18+)

Use the tightest constraint possible. comparable for map keys, cmp.Ordered for sorting, custom interfaces for domain-specific ordering.

type Set[T comparable] map[T]struct{}

func (s Set[T]) Add(v T)          { s[v] = struct{}{} }
func (s Set[T]) Contains(v T) bool { _, ok := s[v]; return ok }

Writing Generic Data Structures — Using Go 1.18+ generics for type-safe containers, understanding constraint satisfaction, and building domain-specific generic types.

Pointer Types

TypeUse CaseZero Value
*TNormal indirection, mutation, optional valuesnil
unsafe.PointerFFI, low-level memory layout (6 spec patterns only)nil
weak.Pointer[T] (1.24+)Caches, canonicalization, weak referencesN/A

Pointer Types Deep Dive — Normal pointers, unsafe.Pointer (the 6 valid spec patterns), and weak.Pointer[T] for GC-safe caches that don't prevent cleanup.

Copy Semantics Quick Reference

TypeCopy BehaviorIndependence
int, float, bool, stringValue (deep copy)Fully independent
array, structValue (deep copy)Fully independent
sliceHeader copied, backing array sharedUse slices.Clone
mapReference copiedUse maps.Clone
channelReference copiedSame channel
*T (pointer)Address copiedSame underlying value
interfaceValue copied (type + value pair)Depends on held type

Third-Party Libraries

For advanced data structures (trees, sets, queues, stacks) beyond the standard library:

  • emirpasic/gods — comprehensive collection library (trees, sets, lists, stacks, maps, queues)
  • deckarep/golang-set — thread-safe and non-thread-safe set implementations
  • gammazero/deque — fast double-ended queue

When using third-party libraries, refer to their official documentation and code examples for current API signatures.

  • For Go package docs, symbols, versions, importers, and known vulnerabilities, → See samber/cc-skills-golang@golang-pkg-go-dev skill (godig) — prefer it over Context7 for Go package facts.
  • To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See samber/cc-skills-golang@golang-gopls skill (gopls).
  • Context7 remains a fallback for docs not indexed on pkg.go.dev.

Cross-References

  • → See samber/cc-skills-golang@golang-performance skill for struct field alignment, memory layout optimization, and cache locality
  • → See samber/cc-skills-golang@golang-safety skill for nil map/slice pitfalls, append aliasing, defensive copying, slices.Clone/Equal
  • → See samber/cc-skills-golang@golang-concurrency skill for channels, sync.Map, sync.Pool, and all sync primitives
  • → See samber/cc-skills-golang@golang-design-patterns skill for string vs []byte vs []rune, iterators, streaming
  • → See samber/cc-skills-golang@golang-structs-interfaces skill for struct composition, embedding, and generics vs any
  • → See samber/cc-skills-golang@golang-code-style skill for slice/map initialization style

Common Mistakes

MistakeFix
Growing a slice in a loop without preallocationEach growth copies the entire backing array — O(n) per growth. Use make([]T, 0, n) or slices.Grow
Using container/list when a slice would sufficeLinked lists have poor cache locality (each node is a separate heap allocation). Benchmark first
bytes.Buffer for pure string buildingBuffer's String() copies the underlying bytes. strings.Builder avoids this copy
unsafe.Pointer stored as uintptr across statementsGC can move the object between statements — the uintptr becomes a dangling reference
Large struct values in maps (copying overhead)Map access copies the entire value. Use map[K]*V for large value types to avoid the copy

References

来自 samber 的更多技能

chrome-extension
samber
使用 Manifest V3 构建 Chrome 扩展的全面指南。当用户提到 Chrome 扩展、浏览器扩展、manifest.json、内容脚本、服务工作者(扩展上下文)、弹出窗口、侧边栏、chrome.runtime、chrome.tabs、chrome.storage、chrome.scripting、后台脚本、MV3、Manifest V3 或任何 Chrome 扩展 API 时,使用此技能。当用户想要向网页注入脚本、在页面与后台之间通信、绕过 CSP 时,也触发此技能。
developmentbrowser-automation
conventional-git
samber
Conventional Commits v1.0.0 分支命名、工作树命名及提交信息标准,适用于 GitHub 和 GitLab 项目。在创建分支、命名工作树、编写提交、生成提交信息、审查分支规范或设置变更日志自动化时使用。当项目需要一致的 Git 历史记录、基于语义化版本控制的发布、可解析的变更日志生成或自动关闭问题时应用。当用户询问如何命名工作树、创建 Git 工作树或...时触发。
developmentcode-reviewdevops
copywriting-cta
samber
设计文章末尾的CTA(置于博客文章、新闻通讯、随笔、文章或任何长文底部的行动号召)。当用户要求撰写、设计、审查或改进文章、博客或随笔底部的CTA;提及“文末CTA”、“文章底部”、“行动号召”、“注册框”、“新闻通讯CTA”、“订阅模块”、“底部该放什么”、“如何让读者订阅/分享/预约通话/购买/...”时,使用此技能。
marketingcreativecommunication
copywriting-hooks
samber
为长篇文章(英文或法文)生成开篇钩子和文章标题——包括博客文章、Substack/Medium/dev.to、领英长文、付费新闻通讯、观点文章、深度报道、技术解析。当用户要求提供钩子、开篇、导语、引言、首句/首段、开场白、accroche、attaque、phrase d'accroche或première phrase时触发——包括让平淡的引言更有冲击力或重写草稿开篇。当用户要求提供文章标题、titre d'article时也触发。
marketingcreativecommunication
copywriting-prose-creator
samber
将某人或品牌的写作方式编码为散文机制(词汇、句法、节奏、结构、标志性手法),独立于情感基调。输出:PROSE.md。三种模式:从SOUL.md + TONE.md + 探索性访谈中构建全新指南;将现有指南适配到新渠道;在编码前审计语料库以提取散文模式。适用场景:为内容工厂制定写作规则,为多写手一致性编码代笔风格,定义禁用词和句子长度目标……
creativecommunicationdocument
copywriting-tone-of-voice-creator
samber
通过发现、声音定义和渠道调制,构建品牌语调指南(TONE.md)。输出包含行为准则的语音属性、NN/g定位、语调调制矩阵、词汇库、机制和渠道规则——供下游内容技能用于撰写符合品牌调性的文案。涵盖B2B SaaS、B2C/D2C、非政府组织、公共部门、咨询、工业、产品驱动、个人及志愿者品牌;研究未覆盖的语境(政治、受监管领域、宗教组织、游戏等)……
marketingcreativecommunication
crxjs
samber
CRXJS Chrome扩展开发 — 为弹出窗口、选项页
developmentbrowser-automation
deep-research
samber
深度研究技能——广泛并行网络搜索、多源验证、置信度追踪、带引用的Markdown报告。支持11种研究类型:市场(TAM/SAM、细分市场、定价、趋势)、领域(行业结构、生态系统、监管环境)、技术(架构、工具、基准测试)、竞争(竞争对手拆解、定位、赢/输分析)、产品(功能分析、评论、路线图信号)、学术(文献综述、引用网络、关键作者)、人物/组织(尽职...
researchweb-scrapingdata-analysis