Go Data Structures logo

Go Data Structures

Community
eduardo-sl
go-data-structures

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

Overview

Publishereduardo-sl
Repositorygo-agent-skills
Skill namego-data-structures
Stars
86
Forks
11
Bundled files
1
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 1 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by eduardo-sl on GitHub. Read the source before you install it.

Installation

Install the Go Data Structures AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/eduardo-sl/go-agent-skills/tree/main/skills/(code-quality)/go-data-structures
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.

Use it in TypingMind

Enable Go Data Structures in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Go Data Structures on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Go Data Structures is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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/heap priority queue, LRU with container/list, reclaiming map memory, a weak.Pointer cache.

Read a reference file only when the summary below is not enough.

1. Nil Slice vs Empty Slice

go
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 b
  • len, cap, range, and append treat all three identically.
  • Prefer the nil slice as the "no elements" value; don't allocate just to return "empty".
  • Exception: JSON. With encoding/json, nil marshals to null and empty to []; if the contract requires [], return an empty slice. The Go 1.27 encoding/json/v2 API 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:

go
// ❌ 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")
}
go
// ❌ 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:

go
// ✅ 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

go
// 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 = v doesn't compile for struct values. Use a map of pointers, or read-modify-write.
  • Deleting during range is safe; inserting during range is unspecified (the new key may or may not be visited).

5. Sets

The idiomatic set is a map with empty-struct values:

go
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]int copies 800 bytes per call — almost always wrong.

7. Choosing a Structure

NeedUse
Ordered collection, growable[]T
Membership / dedupmap[K]struct{}
Key→value lookupmap[K]V
Fixed size, value semantics, comparable[N]T array
FIFO queue (single goroutine)slice with head index, or container/list for heavy churn
Stackslice + append / s[:len(s)-1]
Concurrent map, write-once read-many keyssync.Map — otherwise mutex + map
Priority queue, top-K, schedulercontainer/heap
Fixed-size rolling windowslice used as a ring (index mod len), or container/ring
LRU cachemap[K]*list.Element + container/list
Cache that must not keep values alivemap[K]weak.Pointer[V] (Go 1.24+)
Deduplicate many equal stringsunique.Make (Go 1.23+)
Key type for a custom hash tablemaphash.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. delete and clear keep 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.Builder builds strings without a final copy; it must not be copied once written to. bytes.Buffer is the type for byte-oriented I/O (it is both an io.Reader and an io.Writer); its String() copies.

9. Copy Semantics

TypeAssignment copiesIndependent copy
Basic types, arrays, structs of valuesEverythingAlready independent
SliceHeader (ptr, len, cap)slices.Clone
MapReferencemaps.Clone (shallow)
Pointer, channel, funcReference—
InterfaceType + value wordDepends on the dynamic type

Clones are shallow: a cloned []*User still shares every User. Examples for sections 7-9: references/containers.md.

Verification Checklist

  1. No logic distinguishes nil slice from empty slice; len() used for emptiness
  2. JSON-facing slices explicitly empty (not nil) where the contract requires []
  3. No append to a slice the function doesn't own; copies made explicit
  4. No long-lived subslices of large arrays without slices.Clone/copy
  5. Slices and maps preallocated with capacity when size is known
  6. Comma-ok used wherever "missing" differs from zero value
  7. No writes to possibly-nil maps
  8. Deterministic output paths sort map keys before iteration
  9. Sets built as map[K]struct{} (or map[K]bool for readability)
  10. Arrays only where value semantics or comparability is the point
  11. Long-lived maps that shrink drastically are rebuilt, not just deleted from
  12. Priority queues and LRUs use container/heap / container/list, not ad-hoc sorting

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Go Data Structures AI skill do?

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

Why use Go Data Structures on TypingMind?

Because you install it once and use it with any model. Go Data Structures is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Go Data Structures in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/eduardo-sl/go-agent-skills/tree/main/skills/(code-quality)/go-data-structures. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Go Data Structures?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Go Data Structures?

As many as you like. As long as a model supports skills, you can use Go Data Structures with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Go Data Structures AI skill free?

Yes. It is published on GitHub by eduardo-sl under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇