go-data-structures
Skill85 starsChanged 18 days agoMITView on GitHub
Correct use of Go's built-in data structures: slices (nil vs empty, append semantics, aliasing, preallocation), maps (comma-ok, sets, iteration order), arrays, and choosing between them. Use when: "slice vs array", "nil slice", "empty slice", "preallocate", "map iteration", "use a set in Go", "slice aliasing", "append gotcha", "copy a slice", "sync.Map or mutex". Not for: structures shared across goroutines (go-concurrency-review), allocation profiling (go-performance-review), generic containers (go-design-patterns).
We split this skill into the rules it gives an agent
8 rules. About 0 are common, 3 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 33
Read a reference file only when the summary below is not enough.
- Very specific: line 49
Never distinguish nil from empty in logic — check len(s) == 0.
- Distinctive: line 87
When the final size is known or bounded, allocate once:
- Very specific: line 104
Don't preallocate when the size is unknown — a wrong large cap wastes memory.
- Very specific: line 154
Use arrays for fixed-size data with value semantics: hashes ([32]byte), IPv4 addresses, fixed matrices, map keys.
- Very specific: line 209
No logic distinguishes nil slice from empty slice.
- Very specific: line 212
No long-lived subslices of large arrays without slices.Clone/copy
- Distinctive: line 215
No writes to possibly-nil maps
≈ “Common” is an estimate: at least 1 in 5 of the 308,232 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
Slices and maps look simple and hide the sharpest edges in the language. These rules prevent the aliasing, nil, and iteration bugs that survive code review.
Detailed reference material, loaded on demand:
references/containers.md—container/heappriority queue, LRU withcontainer/list, reclaiming map memory, aweak.Pointercache.
Read a reference file only when the summary below is not enough.
1. Nil Slice vs Empty Slice
var a []int // nil slice — len 0, cap 0, no allocation
b := []int{} // empty slice — len 0, allocated header
c := make([]int, 0) // empty slice — same as blen,cap,range, andappendtreat all three identically.- Prefer the nil slice as the "no elements" value; don't allocate just to return "empty".
- Exception: JSON. With
encoding/json,nilmarshals tonulland empty to[]; if the contract requires[], return an empty slice. The Go 1.27encoding/json/v2API marshals nil as[]by default. - Never distinguish nil from empty in logic — check
len(s) == 0.
2. Append Semantics and Aliasing
append MAY return the same backing array or a new one. Both cases
bite:
// ❌ Bad — result may alias the input
func addSuffix(base []string) []string {
return append(base, "suffix") // if cap(base) > len(base),
} // this WRITES INTO base's array
// ✅ Good — force a copy when the input must not be touched
func addSuffix(base []string) []string {
out := make([]string, len(base), len(base)+1)
copy(out, base)
return append(out, "suffix")
}// ❌ Bad — subslice keeps the whole 64 MB alive
func header(big []byte) []byte {
return big[:512] // backing array is still the full big
}
// ✅ Good — copy the window you keep
func header(big []byte) []byte {
return slices.Clone(big[:512]) // Go 1.21+; or copy() manually
}Rule: a function either owns a slice or copies it. Returning a subslice of a caller's slice, or appending to one, silently shares memory.
3. Preallocation
When the final size is known or bounded, allocate once:
// ✅ Good — one allocation
names := make([]string, 0, len(users))
for _, u := range users {
names = append(names, u.Name)
}
// ❌ Bad — repeated growth and copying
var names []string
for _, u := range users {
names = append(names, u.Name)
}Same for maps: make(map[string]int, len(items)).
Don't preallocate when the size is unknown — a wrong large cap wastes
memory; append growth is fine for cold paths.
4. Map Essentials
// Comma-ok distinguishes "missing" from "zero value"
count, ok := hits[key]
if !ok { /* key absent */ }
// Zero value reads are safe; writes to a nil map PANIC
var m map[string]int
_ = m["x"] // 0, fine
m["x"] = 1 // panic: assignment to entry in nil map — make() first
// Iteration order is RANDOM and differs between runs.
// Sort keys when output must be deterministic:
keys := slices.Sorted(maps.Keys(m)) // Go 1.23+
for _, k := range keys {
fmt.Println(k, m[k])
}- Map values are not addressable:
m[k].Field = vdoesn't compile for struct values. Use a map of pointers, or read-modify-write. - Deleting during
rangeis safe; inserting duringrangeis unspecified (the new key may or may not be visited).
5. Sets
The idiomatic set is a map with empty-struct values:
seen := make(map[string]struct{}, len(items))
for _, it := range items {
if _, dup := seen[it.ID]; dup {
continue
}
seen[it.ID] = struct{}{}
process(it)
}struct{} occupies zero bytes; map[string]bool also works and reads
better when you'll test membership with if seen[id].
6. Arrays vs Slices
- Arrays (
[4]byte) are values: assignment and passing copy the whole array. Comparable with==when elements are comparable. - Use arrays for fixed-size data with value semantics: hashes
(
[32]byte), IPv4 addresses, fixed matrices, map keys. - Everything else is a slice. A function taking
[100]intcopies 800 bytes per call — almost always wrong.
7. Choosing a Structure
| Need | Use |
| Ordered collection, growable | []T |
| Membership / dedup | map[K]struct{} |
| Key→value lookup | map[K]V |
| Fixed size, value semantics, comparable | [N]T array |
| FIFO queue (single goroutine) | slice with head index, or container/list for heavy churn |
| Stack | slice + append / s[:len(s)-1] |
| Concurrent map, write-once read-many keys | sync.Map — otherwise mutex + map |
| Priority queue, top-K, scheduler | container/heap |
| Fixed-size rolling window | slice used as a ring (index mod len), or container/ring |
| LRU cache | map[K]*list.Element + container/list |
| Cache that must not keep values alive | map[K]weak.Pointer[V] (Go 1.24+) |
| Deduplicate many equal strings | unique.Make (Go 1.23+) |
| Key type for a custom hash table | maphash.Comparable / maphash.Hasher (1.24 / 1.27) |
sync.Map is a special-case tool (append-only caches, disjoint key
sets). Default to map + sync.RWMutex; see the concurrency skill for
locking patterns.
8. Memory Behaviour
- Maps never shrink.
deleteandclearkeep the buckets. After a map that once held millions of entries is mostly empty, rebuild it (m = maps.Clone(m)) to give the memory back. clear(s)zeroes a slice's elements but keeps its length;s = s[:0]keeps the backing array for reuse. Neither frees memory.- Popping from a slice of pointers — nil the vacated slot
(
s[n-1] = nil) or the GC still sees the object as reachable. strings.Builderbuilds strings without a final copy; it must not be copied once written to.bytes.Bufferis the type for byte-oriented I/O (it is both anio.Readerand anio.Writer); itsString()copies.
9. Copy Semantics
| Type | Assignment copies | Independent copy |
| Basic types, arrays, structs of values | Everything | Already independent |
| Slice | Header (ptr, len, cap) | slices.Clone |
| Map | Reference | maps.Clone (shallow) |
| Pointer, channel, func | Reference | — |
| Interface | Type + value word | Depends on the dynamic type |
Clones are shallow: a cloned []*User still shares every User.
Examples for sections 7-9: references/containers.md.
Verification Checklist
- No logic distinguishes nil slice from empty slice;
len()used for emptiness - JSON-facing slices explicitly empty (not nil) where the contract requires
[] - No
appendto a slice the function doesn't own; copies made explicit - No long-lived subslices of large arrays without
slices.Clone/copy - Slices and maps preallocated with capacity when size is known
- Comma-ok used wherever "missing" differs from zero value
- No writes to possibly-nil maps
- Deterministic output paths sort map keys before iteration
- Sets built as
map[K]struct{}(ormap[K]boolfor readability) - Arrays only where value semantics or comparability is the point
- Long-lived maps that shrink drastically are rebuilt, not just deleted from
- Priority queues and LRUs use
container/heap/container/list, not ad-hoc sorting
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- h0rn3t/golang-skills★ 7same 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 repository38 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/go-skills.mdcCursor rule
- go-api-designSkill
- go-architecture-reviewSkill
- go-cliSkill
- go-dependency-injectionSkill
- go-design-patternsSkill
- go-graphqlSkill
- go-grpcSkill
- go-interface-designSkill
- go-openapiSkill
- go-project-layoutSkill
- go-code-reviewSkill
- go-coding-standardsSkill
- go-contextSkill
- go-documentationSkill
- go-error-handlingSkill
- go-modernizeSkill
- go-namingSkill
- go-databaseSkill
- go-concurrency-reviewSkill
- go-defensive-codingSkill
- go-observabilitySkill
- go-performance-reviewSkill
- go-security-auditSkill
- go-troubleshootingSkill
- go-test-qualitySkill
- go-test-table-drivenSkill
- git-commitSkill
- go-binary-sizeSkill
- go-build-releaseSkill
- go-ciSkill
- go-dependency-auditSkill
- go-refactoringSkill
- go-semantic-toolsSkill
- go-skills-routerSkill
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.

