go-data-structures
Skill9 starsChanged 4 months agoMITView on GitHub
Use when choosing or operating on Go slices, maps, arrays, strings, or container/* types — including slice internals, capacity growth, preallocation, map buckets, sets via map[T]struct{}, strings.Builder vs bytes.Buffer, generic containers, and the slices/maps standard packages (Go 1.21+). Apply proactively whenever data is being collected, transformed, or copied, even if the user has not asked about allocation.
2 other projects use a version of this.
Adopted by
Most recently taken up by
- eduardo-sl/go-agent-skillstheir own version, first seen Aug 18, 2026
- cxuu/golang-skillstheir own version, first seen Jun 20, 2026
Other versions2 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 2
- cxuu/golang-skills★ 165same name
- eduardo-sl/go-agent-skills★ 72same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository26 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- go-clean-architectureSkill
- go-code-reviewSkill
- go-code-styleSkill
- go-concurrencySkill
- go-contextSkill
- go-control-flowSkill
- go-databaseSkill
- go-declarationsSkill
- go-defensiveSkill
- go-documentationSkill
- go-error-handlingSkill
- go-functional-optionsSkill
- go-functionsSkill
- go-genericsSkill
- go-graphqlSkill
- go-grpcSkill
- go-interfacesSkill
- go-lintingSkill
- go-loggingSkill
- go-namingSkill
- go-observabilitySkill
- go-packagesSkill
- go-performanceSkill
- go-swaggerSkill
- go-testingSkill
The file
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 1 is distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 73
Prefer these over hand-rolled loops — they're tested, generic, and use the fastest available paths.
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Go Data Structures
Pick the structure that fits the access pattern — not the most familiar one. Slices and maps are the workhorses; arrays, container types, and the slices/maps packages cover the rest. Understanding the header layout, growth costs, and copy semantics of each turns most performance questions into one-line decisions.
Core Rules
- Slices and maps are reference types — assigning copies the header, not the data. Use
slices.Clone/maps.Clonefor a true copy. - Preallocate with
make([]T, 0, n)andmake(map[K]V, n)whenever the size is known or estimable. - Always assign the result of
append— the backing array may move. - Use
slicesandmapspackages (Go 1.21+) instead of hand-rolled helpers. map[K]struct{}is the canonical set — zero-byte values, no boolean ambiguity.strings.Builderfor string building,bytes.Bufferwhen you needio.Reader/io.Writer.
Picking a Structure
What do you need?
├─ Ordered, fixed compile-time size → [N]T array
├─ Ordered, dynamic size → []T slice
│ ├─ Known size → make([]T, 0, n)
│ └─ JSON output must be [] → []T{} literal (not nil)
├─ Key/value lookup → map[K]V
│ ├─ Need a set → map[K]struct{}
│ └─ Known size → make(map[K]V, n)
├─ Priority queue / top-k → container/heap
├─ Frequent middle insertion → container/list
├─ Fixed-size rolling window → container/ring
├─ Pure string building → strings.Builder
└─ Read+write of bytes → bytes.BufferSlice Internals
A slice is a 3-word header: pointer, length, capacity. Multiple slices can alias the same backing array — s[1:4] shares memory with s.
Capacity Growth
The exact algorithm has changed across versions; do not rely on it. As of recent Go:
len < 256→ capacity roughly doubles.len ≥ 256→ grows by ~25%.- Each growth allocates a new backing array and copies — O(n) per growth.
Preallocation
users := make([]User, 0, len(ids)) // exact size
results := make([]Result, 0, estimated) // approximate
s = slices.Grow(s, additional) // pre-grow before bulk append (Go 1.21+)slices Package (Go 1.21+)
| Function | Purpose |
Sort, SortFunc, SortStableFunc | sorting |
BinarySearch, BinarySearchFunc | sorted lookup |
Contains, Index, IndexFunc | search |
Compact, CompactFunc | dedupe adjacent equals |
Clone, Equal | safe copy / comparison |
Delete, DeleteFunc | removal preserving order |
Grow | preallocate before append |
Concat (1.22+) | concatenate slices |
Prefer these over hand-rolled loops — they're tested, generic, and use the fastest available paths.
Read references/slices-and-maps.md for capacity growth, aliasing pitfalls, and 2-D slice patterns.
nil vs Empty Slice: The JSON Trap
Both have len == 0 and cap == 0, but they encode differently:
var nilSlice []string // → JSON: null
emptySlice := []string{} // → JSON: []API contracts almost always want []. Initialise the slice explicitly in any struct that gets marshaled to JSON, and treat nil/empty as identical when reading (use len(s) == 0).
For internal computation where nil is never marshaled, the nil slice is conventional and slightly cheaper (no allocation until first append).
Maps
Maps are hash tables with 8-entry buckets and overflow chains. They are reference types — assigning a map copies a pointer.
Preallocation
m := make(map[string]*User, len(users)) // avoids rehashing during populationThe size hint is approximate (it's about bucket count), but it still saves repeated rehashing in the common case.
Sets
type Set[T comparable] map[T]struct{}
func (s Set[T]) Add(v T) { s[v] = struct{}{} }
func (s Set[T]) Has(v T) bool { _, ok := s[v]; return ok }
func (s Set[T]) Remove(v T) { delete(s, v) }struct{} is zero bytes; the set is just the key set of the underlying map.
map[K]bool is also common but ambiguous: did false mean "explicitly excluded" or "not present"? struct{} removes the question.
maps Package (Go 1.21+)
Clone, Equal/EqualFunc, DeleteFunc; Keys, Values, Collect, Insert since 1.23 (iterators).
Read references/strings-bytes-builder.md for string-vs-bytes,
BuildervsBuffer, and rune handling.
Arrays
Fixed-size, value type, copied on assignment. Useful for compile-time-known sizes:
type Digest [32]byte
type IP4 [4]byte
cache := map[[2]int]Result{} // arrays are comparable → usable as map keysFor anything dynamic, use a slice.
container/* and Third-Party
| Package | Use case | Caveat |
container/heap | priority queue, top-K | implement the interface yourself |
container/list | LRU, frequent middle splice | poor cache locality |
container/ring | rolling window, round-robin | fixed size |
bufio | I/O with many small reads/writes | always check Flush errors |
For typed sets/queues/trees beyond the stdlib, prefer well-tested libraries (emirpasic/gods, gammazero/deque) and benchmark before optimising.
Read references/containers-and-pointers.md for heap implementation,
unsafe.Pointer's six valid patterns, andweak.Pointer[T].
Copy Semantics Cheat Sheet
| Type | Copy behaviour |
| primitives, arrays, structs | value (deep for contained value fields) |
| slice | header copied, backing array shared — use slices.Clone |
| map, channel | reference copied — use maps.Clone for maps |
*T, interface | address / (type, value) pair copied |
Anti-Patterns
| Anti-pattern | Why it hurts | Do this instead |
s := append(s, x) ignoring return | Backing array may move; s becomes stale | Always reassign |
var m map[K]V; m[k] = v | nil map panic | m := make(map[K]V) or map[K]V{} |
var s []T then marshal to JSON as [] | Encodes as null | s := []T{} |
make([]T, 0, 10000) "just in case" | Wasted memory | Size by actual data |
m := map[K]bool{} as a set | false is ambiguous | map[K]struct{} |
bytes.Buffer for pure string building | Extra copy in String() | strings.Builder |
| Large struct values in a map | Each lookup copies the value | map[K]*V |
Verification Checklist
- Every
make([]T, ...)andmake(map[K]V, ...)has a capacity hint when the size is known. - Every
appendreassigns its result. - Slices marshaled to JSON are initialised as
[]T{}, notvar s []T. - All "sets" use
map[K]struct{}(or a genericSet[T]wrapper). - No
bytes.Bufferused purely forString()output. - No
*sync.Mutexcopied via struct assignment (go vet copylocks). slices.Clone/maps.Cloneused when handing data to callers that may mutate.
References
- references/slices-and-maps.md — internals, growth, aliasing,
slices/mapspackages - references/strings-bytes-builder.md —
strings.Builder,bytes.Buffer, rune handling - references/containers-and-pointers.md —
container/heap, generic wrappers,unsafe.Pointer,weak.Pointer
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

