golang-data-structures
samber/cc-skills-golang
Understand Go data structure internals to choose and optimize slices, maps, arrays, and containers correctly.
What is golang-data-structures?
Deep reference on Go's built-in and standard library data structures: how slices and maps work internally, when to preallocate, which container/ types to use, and how to work safely with pointers. Use this when designing data structures, optimizing for memory layout and allocation cost, or implementing generic containers.
- Explains slice internals (header, capacity growth algorithm, preallocation strategies) and the slices package (Go 1.21+)
- Documents map internals (hash buckets, overflow chains, rehashing) and maps package functions (Go 1.21+)
- Covers arrays, container/list, container/heap, container/ring, and bufio patterns with guidance on when to use each
- Compares strings.Builder vs bytes.Buffer and shows generic collection patterns with tight constraints
- Details unsafe.Pointer (6 valid spec patterns) and weak.Pointer[T] (Go 1.24+) for caches and weak references
- Provides copy semantics reference for all Go types (value vs reference, independence, cloning)
How to install golang-data-structures
npx skills add https://github.com/samber/cc-skills-golang --skill golang-data-structuresHow to use golang-data-structures
- 1.Consult the Best Practices Summary for immediate guidance on preallocation, container selection, and pointer safety
- 2.Read the relevant deep-dive reference (Slice Internals, Map Internals, Containers, Generics, or Pointers) for your use case
- 3.Use the Copy Semantics Quick Reference table to determine whether assignment creates an independent copy or a shared reference
- 4.Apply preallocation patterns (make with capacity) when size is known or estimable to avoid repeated allocations
- 5.For generic collections, choose the tightest constraint (comparable, cmp.Ordered, or custom interface) that fits your domain
Use cases
- Choosing between slice, array, or container/list for a given access pattern and estimating allocation cost
- Preallocation of slices and maps when bulk-loading data to avoid repeated growth copies and rehashing
- Implementing a priority queue with container/heap or LRU cache with container/list and understanding trade-offs
- Building generic type-safe data structures with appropriate constraints (comparable, cmp.Ordered, custom interfaces)
- Debugging slice aliasing or map reference issues by understanding the header and reference semantics
- Go engineers designing or optimizing data structures for performance-critical code
- Developers implementing generic containers or custom collection types
- Anyone working with unsafe.Pointer or low-level memory layout in Go
- Teams building caches, priority queues, or other specialized data structures
golang-data-structures FAQ
Preallocate with make(T, 0, n) or make(map[K]V, n) whenever the size is known or estimable. This avoids repeated growth copies (O(n) each) and rehashing. If size is unknown, estimate conservatively or use slices.Grow(s, additionalNeeded) before bulk appends.
Use arrays only for fixed, compile-time-known sizes (e.g., hash digests [32]byte, IPv4 addresses [4]byte, matrix dimensions). Arrays are value types and copied entirely on assignment, making them expensive for large sizes. Prefer slices for everything else.
Use strings.Builder for pure string concatenation—it avoids a copy on String(). Use bytes.Buffer when you need io.Reader or io.Writer interfaces or byte manipulation. Both support Grow(n) for preallocation.
Use container/heap for priority queues and top-K problems. Use container/list only when you need frequent middle insertions or removals (LRU caches). Use container/ring for fixed-size circular buffers. For most other cases, slices are simpler and faster.
The Go spec defines 6 safe patterns: (1) *T to unsafe.Pointer, (2) unsafe.Pointer to *T, (3) uintptr to unsafe.Pointer (only in a single expression), (4) pointer arithmetic via uintptr, (5) reflect.SliceHeader/StringHeader, (6) syscall.Syscall. Never store unsafe.Pointer as uintptr across statements—the GC may move the object.
Full instructions (SKILL.md)
Source of truth, from samber/cc-skills-golang.
name: golang-data-structures
description: "Golang data structures — slices (internals, capacity growth, preallocation, slices package), maps (internals, hash buckets, maps package), arrays, container/list/heap/ring, strings.Builder vs bytes.Buffer, generic collections, pointers (unsafe.Pointer, weak.Pointer), and copy semantics. Use when choosing or optimizing Go data structures, implementing generic containers, using container/ packages, unsafe or weak pointers, or questioning slice/map internals. Not for applying optimization patterns once profiling has identified a bottleneck (→ See samber/cc-skills-golang@golang-performance skill)."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
author: samber
version: "1.2.2"
openclaw:
emoji: "🗃"
homepage: https://github.com/samber/cc-skills-golang
requires:
bins:
- go
install: []
allowed-tools: Read Edit Write Glob Grep Bash(go:) Bash(golangci-lint:) Bash(git:) Agent Bash(godig:) Bash(gopls:) LSP mcp__gopls__ mcp__context7__resolve-library-id mcp__context7__query-docs
paths:
- "**/*.go"
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-safetyskill. - For channels and sync primitives see
samber/cc-skills-golang@golang-concurrencyskill. - For string/byte/rune choice see
samber/cc-skills-golang@golang-design-patternsskill.
Best Practices Summary
- 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 - Arrays SHOULD be preferred over slices only for fixed, compile-time-known sizes (hash digests, IPv4 addresses, matrix dimensions)
- 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
- Use
container/heapfor priority queues,container/listonly when frequent middle insertions are needed,container/ringfor fixed-size circular buffers strings.BuilderMUST be preferred for building strings;bytes.BufferMUST be preferred for bidirectional I/O (implements bothio.Readerandio.Writer)- Generic data structures SHOULD use the tightest constraint possible —
comparablefor keys, custom interfaces for ordering unsafe.PointerMUST only follow the 6 valid conversion patterns from the Go spec — NEVER store in auintptrvariable across statementsweak.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+)
| Function | Purpose |
|---|---|
Collect (1.23+) | Build map from iterator |
Insert (1.23+) | Insert entries from iterator |
All (1.23+) | Iterator over all entries |
Keys, Values | Iterators 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
| Package | Data Structure | Best For |
|---|---|---|
container/list | Doubly-linked list | LRU caches, frequent middle insertion/removal |
container/heap | Min-heap (priority queue) | Top-K, scheduling, Dijkstra |
container/ring | Circular buffer | Rolling windows, round-robin |
bufio | Buffered reader/writer/scanner | Efficient 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
| Type | Use Case | Zero Value |
|---|---|---|
*T | Normal indirection, mutation, optional values | nil |
unsafe.Pointer | FFI, low-level memory layout (6 spec patterns only) | nil |
weak.Pointer[T] (1.24+) | Caches, canonicalization, weak references | N/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
| Type | Copy Behavior | Independence |
|---|---|---|
int, float, bool, string | Value (deep copy) | Fully independent |
array, struct | Value (deep copy) | Fully independent |
slice | Header copied, backing array shared | Use slices.Clone |
map | Reference copied | Use maps.Clone |
channel | Reference copied | Same channel |
*T (pointer) | Address copied | Same underlying value |
interface | Value 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 implementationsgammazero/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-devskill (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-goplsskill (gopls). - Context7 remains a fallback for docs not indexed on pkg.go.dev.
Cross-References
- → See
samber/cc-skills-golang@golang-performanceskill for struct field alignment, memory layout optimization, and cache locality - → See
samber/cc-skills-golang@golang-safetyskill for nil map/slice pitfalls, append aliasing, defensive copying,slices.Clone/Equal - → See
samber/cc-skills-golang@golang-concurrencyskill for channels,sync.Map,sync.Pool, and all sync primitives - → See
samber/cc-skills-golang@golang-design-patternsskill forstringvs[]bytevs[]rune, iterators, streaming - → See
samber/cc-skills-golang@golang-structs-interfacesskill for struct composition, embedding, and generics vsany - → See
samber/cc-skills-golang@golang-code-styleskill for slice/map initialization style
Common Mistakes
| Mistake | Fix |
|---|---|
| Growing a slice in a loop without preallocation | Each 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 suffice | Linked lists have poor cache locality (each node is a separate heap allocation). Benchmark first |
bytes.Buffer for pure string building | Buffer's String() copies the underlying bytes. strings.Builder avoids this copy |
unsafe.Pointer stored as uintptr across statements | GC 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
Related skills
More from samber/cc-skills-golang and the wider catalog.

golang-database
Comprehensive Go database access guide for PostgreSQL, MySQL, MariaDB, and SQLite using database/sql, sqlx, or pgx.

golang-dependency-injection
Comprehensive guide to dependency injection patterns and libraries in Go.

golang-dependency-management
Manage Go dependencies: go.mod, go.sum, version selection, conflict resolution, and vulnerability scanning.

golang-design-patterns
Idiomatic Go design patterns: functional options, constructors, graceful shutdown, resilience, and architecture styles.

golang-documentation
Comprehensive documentation guide for Go projects: godoc comments, README, CONTRIBUTING, CHANGELOG, examples, and more.

golang-error-handling
Idiomatic Go error handling: wrapping, inspection, structured logging, and production-grade error tracking.