skills/golang-data-structures/SKILL.md
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.
npx skillsauth add rockcookies/skills golang-data-structuresInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
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.
Built-in and standard library data structures: internals, correct usage, and selection guidance. For safety pitfalls (nil maps, append aliasing, defensive copies) see golang-safety skill. For channels and sync primitives see golang-concurrency skill. For string/byte/rune choice see golang-design-patterns skill.
make(T, 0, n) / make(map[K]V, n) when size is known or estimable — avoids repeated growth copies and rehashingcontainer/heap for priority queues, container/list only when frequent middle insertions are needed, container/ring for fixed-size circular buffersstrings.Builder MUST be preferred for building strings; bytes.Buffer MUST be preferred for bidirectional I/O (implements both io.Reader and io.Writer)comparable for keys, custom interfaces for orderingunsafe.Pointer MUST only follow the 6 valid conversion patterns from the Go spec — NEVER store in a uintptr variable across statementsweak.Pointer[T] (Go 1.24+) SHOULD be used for caches and canonicalization maps to allow GC to reclaim entriesA slice is a 3-word header: pointer, length, capacity. Multiple slices can share a backing array (→ see golang-safety for aliasing traps and the header diagram).
= 256 elements: grows by ~25% (
newcap += (newcap + 3*256) / 4)
// 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 golang-safety skill.
Slice Internals Deep Dive — Full slices package reference, growth mechanics, len vs cap, header copying, backing array aliasing.
Maps are hash tables with 8-entry buckets and overflow chains. They are reference types — assigning a map copies the pointer, not the data.
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 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.
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).
| 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.
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
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.
| 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.
| 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 |
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 queueWhen using third-party libraries, refer to their official documentation and code examples for current API signatures. Context7 can help as a discoverability platform.
golang-performance skill for struct field alignment, memory layout optimization, and cache localitygolang-safety skill for nil map/slice pitfalls, append aliasing, defensive copying, slices.Clone/Equalgolang-concurrency skill for channels, sync.Map, sync.Pool, and all sync primitivesgolang-design-patterns skill for string vs []byte vs []rune, iterators, streaminggolang-structs-interfaces skill for struct composition, embedding, and generics vs anygolang-code-style skill for slice/map initialization style| 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 |
development
Vue 3 debugging and error handling for runtime errors, warnings, async failures, and SSR/hydration issues. Use when diagnosing or fixing Vue issues.
development
MUST be used for Vue.js tasks. Strongly recommends Composition API with `<script setup>` and TypeScript as the standard approach. Covers Vue 3, SSR, Volar, vue-tsc. Load for any Vue, .vue files, Vue Router, Pinia, or Vite with Vue work. ALWAYS use Composition API unless the project explicitly requires Options API.
development
GORM Gen 类型安全 DAO 代码生成,基于 github.com/rockcookies/go-gen(rockcookies fork)。涵盖代码生成配置、模型生成、查询构建、增删改查、关联关系、动态 SQL 注解、事务处理、datatypes 自定义字段类型(JSON/JSONMap/JSONSlice/JSONType/Date/UUID)、soft_delete 软删除插件(unix 时间戳/flag 模式),以及 fork 专有功能:Tmpl 运行时模板覆写(18 个模板)、Unsafe 底层方法(UnsafeSetDB/Alias/ModelType/TableName)、IGenericsDo[T,E] 泛型接口。使用时机:需要从数据库生成 DAO 代码(GenerateModel/GenerateModelAs)、编写 DAL 查询(DO 链式调用、DaoScope、事务、关联加载)、配置生成器(gen.Config、ModelOpt、FieldGORMTag、FieldModify、FieldType、Tmpl 自定义模板)、使用 datatypes(JSONMap、JSONSlice、JSONQuery、JSONSet)或 soft_delete(DeletedAt、softDelete:milli、deleteOpts)时使用本技能。当用户消息中包含以下任一关键词(go-gen、gorm-gen、GenerateModelAs、ModelOpt、FieldGORMTag、FieldModify、DaoScope、LoadOneToMany、LoadManyToMany、IGenericsDo、UnsafeSetDB、datatypes、JSONMap、JSONSlice、JSONQuery、soft_delete、softDelete、DeletedAt),或用户明确请求 GORM Gen 代码生成/DAO 编写时触发本技能。
development
轻量级 Go HTTP 客户端库,基于 github.com/rockcookies/go-fetch(零外部依赖)。涵盖 Dispatcher 初始化与中间件、Request 链式构建(RequestFunc 与 Middleware 分层)、Response 解码(JSON/XML/流)、请求体编码(JSON/XML/Form/Multipart/BodyGet)、URL 参数(PrepareURLMiddleware/URLOptions)、Header/Cookie 管理(ApplyHeader/ApplyCookie 与 Context)、中间件组合(Dispatcher/Request/Do 三层)、HTTP 交换日志(dump.New/dump.Transport/过滤器/WithRequestRedactor/WithResponseRedactor/SlogWriter)。使用时机:需要发起 HTTP 请求(GET/POST/PUT/PATCH/DELETE,均需 context.Context)、上传文件(Multipart/GetReader)、配置全局认证头(dispatcher.Use)、记录 HTTP 交换日志(dump.New、WithFilter、DefaultRedactor)、构建可复用的请求基础(Request.Clone)时使用本技能。当用户消息中包含以下任一关键词(go-fetch、NewDispatcher、NewDispatcherWithTransport、RequestFunc、PreFuncs、UseFuncs、BodyGet、MultipartField、dump.New、WithFilter、WithRequestRedactor、WithResponseRedactor、DefaultRedactor、DumpOptions、SlogWriter、URLOptions、PrepareURLMiddleware、PathParams、SetURLOptions、WithURLOptions、ApplyHeader、SetHeaderOptions、WithHeaderOptions、ApplyCookie、SetCookieOptions、WithCookieOptions、HandlerFunc、fetch.Handler、fetch.Middleware、dispatcher.Use、resp.Close、resp.JSON、resp.XML),或用户明确请求 go-fetch HTTP 客户端用法时触发本技能。