golang-data-structures

samber/cc-skills-golang · updated Apr 8, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/samber/cc-skills-golang --skill golang-data-structures
0 commentsdiscussion
summary

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.

skill.md

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-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.

Best Practices Summary

  1. 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
  2. Arrays SHOULD be preferred over slices only for fixed, compile-time-known sizes (hash digests, IPv4 addresses, matrix dimensions)
  3. 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
  4. Use container/heap for priority queues, container/list only when frequent middle insertions are needed, container/ring for fixed-size circular buffers
  5. strings.Builder MUST be preferred for building strings; bytes.Buffer MUST be preferred for bidirectional I/O (implements both io.Reader and io.Writer)
  6. Generic data structures SHOULD use the tightest constraint possible — comparable for keys, custom interfaces for ordering
  7. unsafe.Pointer MUST only follow the 6 valid conversion patterns from the Go spec — NEVER store in a uintptr variable across statements
  8. weak.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 implementations
  • gammazero/deque — fast double-ended queue

When using third-party libraries, refer to their official documentation and code examples for current API signatures. Context7 can help as a discoverability platform.

Cross-References

  • → See samber/cc-skills-golang@golang-performance skill for struct field alignment, memory layout optimization, and cache locality
  • → See samber/cc-skills-golang@golang-safety skill for nil map/slice pitfalls, append aliasing, defensive copying, slices.Clone/Equal
  • → See samber/cc-skills-golang@golang-concurrency skill for channels, sync.Map, sync.Pool, and all sync primitives
  • → See samber/cc-skills-golang@golang-design-patterns skill for string vs []byte vs []rune, iterators, streaming
  • → See samber/cc-skills-golang@golang-structs-interfaces skill for struct composition, embedding, and generics vs any
  • → See samber/cc-skills-golang@golang-code-style skill 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

how to use golang-data-structures

How to use golang-data-structures on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add golang-data-structures
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/samber/cc-skills-golang --skill golang-data-structures

The skills CLI fetches golang-data-structures from GitHub repository samber/cc-skills-golang and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/golang-data-structures

Reload or restart Cursor to activate golang-data-structures. Access the skill through slash commands (e.g., /golang-data-structures) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.647 reviews
  • Ren Shah· Dec 28, 2024

    I recommend golang-data-structures for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Pratham Ware· Dec 24, 2024

    Keeps context tight: golang-data-structures is the kind of skill you can hand to a new teammate without a long onboarding doc.

  • Charlotte Abbas· Dec 20, 2024

    golang-data-structures reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Aditi Gupta· Dec 4, 2024

    Useful defaults in golang-data-structures — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Hiroshi Mehta· Nov 23, 2024

    Registry listing for golang-data-structures matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Ren Desai· Nov 19, 2024

    golang-data-structures reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Hiroshi Menon· Nov 11, 2024

    I recommend golang-data-structures for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Ren Jackson· Nov 11, 2024

    Keeps context tight: golang-data-structures is the kind of skill you can hand to a new teammate without a long onboarding doc.

  • Liam Flores· Oct 14, 2024

    golang-data-structures reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Ren Khanna· Oct 10, 2024

    Registry listing for golang-data-structures matched our evaluation — installs cleanly and behaves as described in the markdown.

showing 1-10 of 47

1 / 5