{"id":"55560473-4e53-46e6-84f3-78a461c3ea09","shortId":"P2YbU3","kind":"skill","title":"golang-data-structures","tagline":"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 sem","description":"**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.\n\n# Go Data Structures\n\nBuilt-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.\n\n## Best Practices Summary\n\n1. **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\n2. **Arrays** SHOULD be preferred over slices only for fixed, compile-time-known sizes (hash digests, IPv4 addresses, matrix dimensions)\n3. **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\n4. **Use `container/heap`** for priority queues, **`container/list`** only when frequent middle insertions are needed, **`container/ring`** for fixed-size circular buffers\n5. **`strings.Builder`** MUST be preferred for building strings; **`bytes.Buffer`** MUST be preferred for bidirectional I/O (implements both `io.Reader` and `io.Writer`)\n6. Generic data structures SHOULD use the **tightest constraint** possible — `comparable` for keys, custom interfaces for ordering\n7. **`unsafe.Pointer`** MUST only follow the 6 valid conversion patterns from the Go spec — NEVER store in a `uintptr` variable across statements\n8. **`weak.Pointer[T]`** (Go 1.24+) SHOULD be used for caches and canonicalization maps to allow GC to reclaim entries\n\n## Slice Internals\n\nA 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).\n\n### Capacity Growth\n\n- < 256 elements: capacity doubles\n- > = 256 elements: grows by ~25% (`newcap += (newcap + 3*256) / 4`)\n- Each growth copies the entire backing array — O(n)\n\n### Preallocation\n\n```go\n// Exact size known\nusers := make([]User, 0, len(ids))\n\n// Approximate size known\nresults := make([]Result, 0, estimatedCount)\n\n// Pre-grow before bulk append (Go 1.21+)\ns = slices.Grow(s, additionalNeeded)\n```\n\n### `slices` Package (Go 1.21+)\n\nKey functions: `Sort`/`SortFunc`, `BinarySearch`, `Contains`, `Compact`, `Grow`. For `Clone`, `Equal`, `DeleteFunc` → see `samber/cc-skills-golang@golang-safety` skill.\n\n**[Slice Internals Deep Dive](./references/slice-internals.md)** — Full `slices` package reference, growth mechanics, `len` vs `cap`, header copying, backing array aliasing.\n\n## Map Internals\n\nMaps are hash tables with 8-entry buckets and overflow chains. They are reference types — assigning a map copies the pointer, not the data.\n\n### Preallocation\n\n```go\nm := make(map[string]*User, len(users)) // avoids rehashing during population\n```\n\n### `maps` Package Quick Reference (Go 1.21+)\n\n| Function          | Purpose                      |\n| ----------------- | ---------------------------- |\n| `Collect` (1.23+) | Build map from iterator      |\n| `Insert` (1.23+)  | Insert entries from iterator |\n| `All` (1.23+)     | Iterator over all entries    |\n| `Keys`, `Values`  | Iterators over keys/values   |\n\nFor `Clone`, `Equal`, sorted iteration → see `samber/cc-skills-golang@golang-safety` skill.\n\n**[Map Internals Deep Dive](./references/map-internals.md)** — 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.\n\n## Arrays\n\nFixed-size, value types. Copied entirely on assignment. Use for compile-time-known sizes:\n\n```go\ntype Digest [32]byte           // fixed-size, value type\nvar grid [3][3]int             // multi-dimensional\ncache := map[[2]int]Result{}   // arrays are comparable — usable as map keys\n```\n\nPrefer slices for everything else — arrays cannot grow and pass by value (expensive for large sizes).\n\n## container/ Standard Library\n\n| Package | Data Structure | Best For |\n| --- | --- | --- |\n| `container/list` | Doubly-linked list | LRU caches, frequent middle insertion/removal |\n| `container/heap` | Min-heap (priority queue) | Top-K, scheduling, Dijkstra |\n| `container/ring` | Circular buffer | Rolling windows, round-robin |\n| `bufio` | Buffered reader/writer/scanner | Efficient I/O with small reads/writes |\n\nContainer types use `any` (no type safety) — consider generic wrappers. **[Container Patterns, bufio, and Examples](./references/containers.md)** — When to use each container type, generic wrappers to add type safety, and `bufio` patterns for efficient I/O.\n\n## strings.Builder vs bytes.Buffer\n\nUse `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](./references/containers.md)**\n\n## Generic Collections (Go 1.18+)\n\nUse the tightest constraint possible. `comparable` for map keys, `cmp.Ordered` for sorting, custom interfaces for domain-specific ordering.\n\n```go\ntype Set[T comparable] map[T]struct{}\n\nfunc (s Set[T]) Add(v T)          { s[v] = struct{}{} }\nfunc (s Set[T]) Contains(v T) bool { _, ok := s[v]; return ok }\n```\n\n**[Writing Generic Data Structures](./references/generics.md)** — Using Go 1.18+ generics for type-safe containers, understanding constraint satisfaction, and building domain-specific generic types.\n\n## Pointer Types\n\n| Type | Use Case | Zero Value |\n| --- | --- | --- |\n| `*T` | Normal indirection, mutation, optional values | `nil` |\n| `unsafe.Pointer` | FFI, low-level memory layout (6 spec patterns only) | `nil` |\n| `weak.Pointer[T]` (1.24+) | Caches, canonicalization, weak references | N/A |\n\n**[Pointer Types Deep Dive](./references/pointers.md)** — Normal pointers, `unsafe.Pointer` (the 6 valid spec patterns), and `weak.Pointer[T]` for GC-safe caches that don't prevent cleanup.\n\n## Copy Semantics Quick Reference\n\n| Type | Copy Behavior | Independence |\n| --- | --- | --- |\n| `int`, `float`, `bool`, `string` | Value (deep copy) | Fully independent |\n| `array`, `struct` | Value (deep copy) | Fully independent |\n| `slice` | Header copied, backing array shared | Use `slices.Clone` |\n| `map` | Reference copied | Use `maps.Clone` |\n| `channel` | Reference copied | Same channel |\n| `*T` (pointer) | Address copied | Same underlying value |\n| `interface` | Value copied (type + value pair) | Depends on held type |\n\n## Third-Party Libraries\n\nFor advanced data structures (trees, sets, queues, stacks) beyond the standard library:\n\n- **`emirpasic/gods`** — comprehensive collection library (trees, sets, lists, stacks, maps, queues)\n- **`deckarep/golang-set`** — thread-safe and non-thread-safe set implementations\n- **`gammazero/deque`** — fast double-ended queue\n\nWhen using third-party libraries, refer to their official documentation and code examples for current API signatures. Context7 can help as a discoverability platform.\n\n## Cross-References\n\n- → See `samber/cc-skills-golang@golang-performance` skill for struct field alignment, memory layout optimization, and cache locality\n- → See `samber/cc-skills-golang@golang-safety` skill for nil map/slice pitfalls, append aliasing, defensive copying, `slices.Clone`/`Equal`\n- → See `samber/cc-skills-golang@golang-concurrency` skill for channels, `sync.Map`, `sync.Pool`, and all sync primitives\n- → See `samber/cc-skills-golang@golang-design-patterns` skill for `string` vs `[]byte` vs `[]rune`, iterators, streaming\n- → See `samber/cc-skills-golang@golang-structs-interfaces` skill for struct composition, embedding, and generics vs `any`\n- → See `samber/cc-skills-golang@golang-code-style` skill for slice/map initialization style\n\n## Common Mistakes\n\n| Mistake | Fix |\n| --- | --- |\n| 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` |\n| Using `container/list` when a slice would suffice | Linked lists have poor cache locality (each node is a separate heap allocation). Benchmark first |\n| `bytes.Buffer` for pure string building | Buffer's `String()` copies the underlying bytes. `strings.Builder` avoids this copy |\n| `unsafe.Pointer` stored as `uintptr` across statements | GC can move the object between statements — the `uintptr` becomes a dangling reference |\n| 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 |\n\n## References\n\n- [Go Data Structures (Russ Cox)](https://research.swtch.com/godata)\n- [The Go Memory Model](https://go.dev/ref/mem)\n- [Effective Go](https://go.dev/doc/effective_go)","tags":["golang","data","structures","skills","samber","agent","agent-skills","antigravity","claude","claude-code","code","codex"],"capabilities":["skill","source-samber","skill-golang-data-structures","topic-agent","topic-agent-skills","topic-antigravity","topic-claude","topic-claude-code","topic-code","topic-codex","topic-coding","topic-copilot","topic-cursor","topic-gemini","topic-gemini-cli-extension"],"categories":["cc-skills-golang"],"synonyms":[],"warnings":[],"endpointUrl":"https://skills.sh/samber/cc-skills-golang/golang-data-structures","protocol":"skill","transport":"skills-sh","auth":{"type":"none","details":{"cli":"npx skills add samber/cc-skills-golang","source_repo":"https://github.com/samber/cc-skills-golang","install_from":"skills.sh"}},"qualityScore":"0.700","qualityRationale":"deterministic score 0.70 from registry signals: · indexed on github topic:agent-skills · 1725 github stars · SKILL.md body (8,981 chars)","verified":false,"liveness":"unknown","lastLivenessCheck":null,"agentReviews":{"count":0,"score_avg":null,"cost_usd_avg":null,"success_rate":null,"latency_p50_ms":null,"narrative_summary":null,"summary_updated_at":null},"enrichmentModel":"deterministic:skill-github:v1","enrichmentVersion":1,"enrichedAt":"2026-05-18T18:53:00.503Z","embedding":null,"createdAt":"2026-04-18T20:32:02.695Z","updatedAt":"2026-05-18T18:53:00.503Z","lastSeenAt":"2026-05-18T18:53:00.503Z","tsv":"'/doc/effective_go)':1200 '/godata)':1188 '/ref/mem)':1195 '/references/containers.md':665,712 '/references/generics.md':771 '/references/map-internals.md':516 '/references/pointers.md':829 '/references/slice-internals.md':416 '0':132,367,376,1094 '1':124 '1.18':716,774 '1.21':385,393,475 '1.23':479,485,491 '1.24':288,819 '2':151,579 '25':344 '256':336,340,348 '3':172,309,347,571,572 '32':562 '4':204,349 '5':225 '6':245,268,812,834 '7':262 '8':284,438 'access':66,1163 'across':282,1140 'add':675,748 'additionalneed':389 'address':169,895 'advanc':915 'algorithm':182 'alias':91,328,430,1008 'align':990 'alloc':63,203,1117 'allow':298 'altern':541 'api':969 'append':90,383,1007 'approxim':370 'array':21,152,201,321,356,429,542,582,594,868,879,1086 'assign':448,551 'avoid':145,466,693,1133,1177 'back':200,320,355,428,878,1085 'becom':1151 'behavior':857 'benchmark':1118 'best':121,611 'beyond':922 'bidirect':238 'binarysearch':398 'bool':761,861 'bucket':18,440,524 'buffer':224,636,643,1125 'bufio':642,662,679 'build':231,480,785,1124 'built':72 'built-in':71 'bulk':382 'byte':563,703,1037,1131 'bytes.buffer':25,233,686,697,1120 'cach':293,577,619,820,845,995,1109 'cannot':595 'canonic':295,821 'cap':425 'capac':10,177,314,334,338 'case':795 'chain':443,526 'chang':183,189 'channel':101,888,892,1020 'choic':113 'choos':46 'circular':223,635 'cleanup':850 'clone':403,502 'cmp.ordered':726 'code':192,965,1061 'collect':27,478,714,928 'common':1068 'compact':400 'compar':255,537,584,722,740 'comparison':711 'compil':162,555 'compile-time-known':161,554 'composit':1051 'comprehens':927 'concaten':692 'concurr':109,1017 'consid':657 'constraint':253,720,782 'contain':399,605,650,660,670,758,780 'container/heap':206,623 'container/list':210,613,1099 'container/list/heap/ring':22 'container/ring':218,634 'context7':971 'convers':270 'copi':32,93,148,352,427,451,548,694,851,856,865,872,877,885,890,896,902,1010,1082,1128,1135,1160,1164,1179 'correct':80 'cost':64 'cox':1185 'cross':979 'cross-refer':978 'current':968 'custom':258,729 'dangl':1153 'data':3,6,42,69,77,247,456,523,609,769,916,1182 'deckarep/golang-set':936 'deep':414,514,827,864,871 'defens':92,1009 'deletefunc':405 'depend':195,906 'design':118,1031 'detail':709 'diagram':333 'digest':167,561 'dijkstra':633 'dimens':171 'dimension':576 'discover':976 'dive':415,515,828 'document':963 'domain':733,787 'domain-specif':732,786 'doubl':339,950 'double-end':949 'doubli':615 'doubly-link':614 'effect':1196 'effici':645,682 'element':337,341 'els':593 'embed':1052 'emirpasic/gods':926 'end':951 'engin':39 'entir':354,549,1084,1166 'entri':302,439,487,495 'equal':404,503,1012 'estim':144 'estimatedcount':377 'everyth':592 'exact':361 'exampl':664,966 'expens':601 'familiar':56 'fast':948 'ffi':806 'field':989 'first':1119 'fix':160,221,544,565,1071 'fixed-s':220,543,564 'float':860 'follow':266 'frequent':213,620 'full':417 'fulli':866,873 'func':744,754 'function':395,476 'gammazero/deque':947 'gc':299,843,1142 'gc-safe':842 'generic':26,246,658,672,713,768,775,789,1054 'go':38,68,185,274,287,360,384,392,458,474,518,559,715,736,773,1181,1190,1197 'go.dev':1194,1199 'go.dev/doc/effective_go)':1198 'go.dev/ref/mem)':1193 'golang':2,5,97,108,117,325,409,509,984,1000,1016,1030,1045,1060 'golang-code-styl':1059 'golang-concurr':107,1015 'golang-data-structur':1 'golang-design-pattern':116,1029 'golang-perform':983 'golang-safeti':96,324,408,508,999 'golang-structs-interfac':1044 'grid':570 'grow':342,380,401,596,707,1072 'growth':11,147,178,181,335,351,421,1081,1090 'guidanc':84 'hash':17,166,435,522 'header':311,332,426,876 'heap':626,1116 'held':908 'help':973 'i/o':239,646,683 'id':369 'implement':240,946 'independ':858,867,874 'indirect':800 'initi':1066 'insert':215,484,486 'insertion/removal':622 'int':573,580,859 'interfac':259,730,900,1047 'intern':9,16,44,79,304,413,432,513 'io.reader':242,701 'io.writer':244 'ipv4':168 'iter':483,489,492,498,505,1040 'job':52 'k':136,631,1170 'key':257,394,496,588,725 'keys/values':500 'known':142,164,363,372,557 'larg':603,1155,1173 'layout':62,811,992 'len':368,423,464 'length':313 'level':809 'librari':76,607,913,925,929,958 'link':616,1105 'list':617,932,1106 'local':996,1110 'loop':1077 'low':808 'low-level':807 'lru':618 'm':459 'make':130,134,365,374,460,1092 'manipul':704 'map':15,19,89,128,135,296,431,433,450,461,470,481,512,519,528,538,578,587,724,741,883,934,1159,1162,1169 'map/slice':1005 'maps.clone':887 'matrix':170 'may':188 'mechan':422 'memori':61,810,991,1191 'middl':214,621 'min':625 'min-heap':624 'mistak':1069,1070 'model':1192 'move':1144 'multi':575 'multi-dimension':574 'multipl':315 'must':227,234,264 'mutat':801 'n':133,138,358,708,1088,1095 'n/a':824 'need':217,700 'never':173,276,529 'new':199 'newcap':345,346 'nil':88,804,816,1004 'node':1112 'non':942 'non-thread-saf':941 'normal':799,830 'o':357,1087 'object':1146 'offici':962 'ok':762,766 'one':57 'optim':993 'option':802 'order':261,735 'overflow':442,525 'overhead':1161 'packag':14,20,391,419,471,608 'pair':905 'parti':912,957 'pass':598 'pattern':67,119,271,661,680,814,837,1032 'per':1089 'perform':539,985 'persona':34 'pitfal':87,1006 'platform':977 'pointer':28,312,453,791,825,831,894 'poor':1108 'popul':469 'possibl':254,721 'practic':122 'pre':379 'pre-grow':378 'prealloc':12,125,359,457,1079 'prefer':155,229,236,589 'prevent':849 'primit':104,1026 'prioriti':208,627 'pure':690,1122 'purpos':477 'queue':209,628,920,935,952 'quick':472,853 'reader/writer/scanner':644 'reads/writes':649 'reason':59 'reclaim':301 'refer':420,446,473,823,854,884,889,959,980,1154,1180 'rehash':150,467 'reli':174 'repeat':146 'research.swtch.com':1187 'research.swtch.com/godata)':1186 'result':373,375,581 'return':765 'right':48 'robin':641 'roll':637 'round':640 'round-robin':639 'rune':1039 'russ':1184 'safe':779,844,939,944 'safeti':86,98,326,410,510,656,677,1001 'samber/cc-skills-golang':95,106,115,323,407,507,982,998,1014,1028,1043,1058 'satisfact':783 'schedul':632 'see':94,105,114,322,406,506,981,997,1013,1027,1042,1057 'select':83 'sem':33 'semant':852 'separ':1115 'set':738,746,756,919,931,945 'share':318,880 'shrink':530 'signatur':970 'size':140,165,222,362,371,545,558,566,604 'skill':99,110,120,411,511,986,1002,1018,1033,1048,1063 'skill-golang-data-structures' 'slice':8,13,126,157,176,303,306,316,390,412,418,590,875,1074,1102 'slice/map':1065 'slices.clone':882,1011 'slices.grow':387,1097 'small':648 'sort':396,504,728 'sortfunc':397 'source-samber' 'spec':275,813,836 'specif':734,788 'stack':921,933 'standard':75,606,924 'statement':283,1141,1148 'store':277,520,1137 'stream':1041 'string':232,462,691,696,862,1035,1123,1127 'string/byte/rune':112 'strings.builder':23,226,684,688,1132 'struct':743,753,869,988,1046,1050,1156 'structur':4,7,43,49,70,78,248,610,770,917,1183 'style':1062,1067 'suffic':1104 'summari':123 'support':706 'sync':103,1025 'sync.map':1021 'sync.pool':1022 'tabl':436 'third':911,956 'third-parti':910,955 'thread':938,943 'thread-saf':937 'tightest':252,719 'time':163,179,556 'top':630 'top-k':629 'topic-agent' 'topic-agent-skills' 'topic-antigravity' 'topic-claude' 'topic-claude-code' 'topic-code' 'topic-codex' 'topic-coding' 'topic-copilot' 'topic-cursor' 'topic-gemini' 'topic-gemini-cli-extension' 'trap':329 'tree':918,930 'type':447,547,560,568,651,655,671,676,737,778,790,792,793,826,855,903,909,1175 'type-saf':777 'uintptr':280,1139,1150 'under':898,1130 'understand':41,781 'unsafe.pointer':29,263,805,832,1136 'usabl':585 'usag':81 'use':205,250,291,552,652,668,687,717,772,794,881,886,954,1091,1098,1168 'user':364,366,463,465 'v':137,749,752,759,764,1171 'valid':269,835 'valu':497,546,567,600,797,803,863,870,899,901,904,1157,1167,1174 'var':569 'variabl':281 'version':186 'vs':24,424,685,1036,1038,1055 'weak':822 'weak.pointer':30,285,817,839 'window':638 'without':1078 'word':310 'would':1103 'wrapper':659,673 'write':767 'zero':796","prices":[{"id":"95f29d53-ae50-4cce-b464-83fda4cb5a15","listingId":"55560473-4e53-46e6-84f3-78a461c3ea09","amountUsd":"0","unit":"free","nativeCurrency":null,"nativeAmount":null,"chain":null,"payTo":null,"paymentMethod":"skill-free","isPrimary":true,"details":{"org":"samber","category":"cc-skills-golang","install_from":"skills.sh"},"createdAt":"2026-04-18T20:32:02.695Z"}],"sources":[{"listingId":"55560473-4e53-46e6-84f3-78a461c3ea09","source":"github","sourceId":"samber/cc-skills-golang/golang-data-structures","sourceUrl":"https://github.com/samber/cc-skills-golang/tree/main/skills/golang-data-structures","isPrimary":false,"firstSeenAt":"2026-04-18T21:55:06.946Z","lastSeenAt":"2026-05-18T18:53:00.503Z"},{"listingId":"55560473-4e53-46e6-84f3-78a461c3ea09","source":"skills_sh","sourceId":"samber/cc-skills-golang/golang-data-structures","sourceUrl":"https://skills.sh/samber/cc-skills-golang/golang-data-structures","isPrimary":true,"firstSeenAt":"2026-04-18T20:32:02.695Z","lastSeenAt":"2026-05-07T22:40:26.986Z"}],"details":{"listingId":"55560473-4e53-46e6-84f3-78a461c3ea09","quickStartSnippet":null,"exampleRequest":null,"exampleResponse":null,"schema":null,"openapiUrl":null,"agentsTxtUrl":null,"citations":[],"useCases":[],"bestFor":[],"notFor":[],"kindDetails":{"org":"samber","slug":"golang-data-structures","github":{"repo":"samber/cc-skills-golang","stars":1725,"topics":["agent","agent-skills","ai","antigravity","claude","claude-code","code","codex","coding","copilot","cursor","gemini","gemini-cli-extension","openclaw","opencode","plugin","skills","skillsmp","vibe-coding"],"license":"mit","html_url":"https://github.com/samber/cc-skills-golang","pushed_at":"2026-05-18T17:36:00Z","description":"🧑‍🎨 A collection of Golang agentic skills that works","skill_md_sha":"087f0fd4cee3cba5b077f402ffae1e161ea1ec92","skill_md_path":"skills/golang-data-structures/SKILL.md","default_branch":"main","skill_tree_url":"https://github.com/samber/cc-skills-golang/tree/main/skills/golang-data-structures"},"layout":"multi","source":"github","category":"cc-skills-golang","frontmatter":{"name":"golang-data-structures","license":"MIT","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.","compatibility":"Designed for Claude Code or similar AI coding agents, and for projects using Golang."},"skills_sh_url":"https://skills.sh/samber/cc-skills-golang/golang-data-structures"},"updatedAt":"2026-05-18T18:53:00.503Z"}}