К основному содержанию
скилл CX Codex

go-data-structures · eduardo-sl — скилл для Claude Code: структуры Go

Скилл помогает выбирать и безопасно использовать слайсы, карты и массивы в Go. Пригодится, когда нужно разобраться с append, nil-слайсами или порядком обхода карты.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add eduardo-sl/go-agent-skills --skill go-data-structures -a claude-code
Открыть на GitHub

Что делает go-data-structures

Скилл объясняет, когда брать слайс, карту или массив, и разбирает их поведение на практических примерах. Он помогает избежать случайного совместного использования памяти после append, отличать отсутствующий ключ карты от нулевого значения и учитывать, что порядок обхода карты меняется между запусками.

В материалах есть рекомендации по предварительному выделению ёмкости, множествам на основе map и копированию слайсов. Для известных размеров предварительное выделение уместно, а слишком большая ёмкость расходует память. Для обычной синхронизации скилл советует карту с sync.RWMutex; sync.Map оставляет для особых сценариев.

Для работы нужен Go toolchain. Скилл рассчитан на проекты на Go, а не на разбор конкурентного доступа: для структур, совместно используемых горутинами, в описании указан отдельный go-concurrency-review.

Какие задачи решает

  • выбрать между слайсом и массивом для фиксированных данных
  • найти причину изменения исходного слайса после append
  • различить nil-слайс и пустой слайс при JSON-кодировании
  • сделать порядок вывода элементов карты детерминированным
  • выбрать между sync.Map и картой с мьютексом

Примеры запросов агенту

  • Проверь, безопасно ли эта функция добавляет элемент к исходному слайсу.
  • Объясни, почему пустой список кодируется как null, и как получить [].
  • Проверь обход этой карты: нужен одинаковый порядок вывода при каждом запуске.

Как установить go-data-structures

1Через Skills CLI (Vercel)

npx skills add eduardo-sl/go-agent-skills --skill go-data-structures -a claude-code

2Вручную: положить файлы

~/.claude/skills/go-data-structures/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/go-data-structures/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о go-data-structures

Как установить go-data-structures в Claude Code?

Выполните npx skills add eduardo-sl/go-agent-skills --skill go-data-structures -a claude-code. Файл скилла устанавливается в ~/.claude/skills/go-data-structures/SKILL.md.

Что делает go-data-structures?

Помогает выбирать встроенные структуры Go и избегать ошибок со слайсами, картами и массивами. В частности, разбирает алиасинг после append и случайный порядок обхода карты.

Когда использовать sync.Map, а когда мьютекс с картой?

Скилл отводит sync.Map особым сценариям, например кэшу с записью без изменений или непересекающимся наборам ключей. В остальных случаях рекомендует обычную карту с sync.RWMutex.

Исходный текст

SKILL.md · MIT
---
name: go-data-structures
description: >
  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).
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents working on Go projects. Requires the Go toolchain.
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(gofmt:*)
metadata:
  author: eduardo-sl
  version: "1.2.0"
---

# 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

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

| 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

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

© eduardo-sl · MIT · eduardo-sl/go-agent-skills

Похожие скиллы

Все скиллы по теме «Языки программирования» →

Сначала — go-data-structures от других авторов.

go-data-structures cxuu Скилл для ИИ-агента, который подсказывает идиомы Go при работе со срезами, картами и массивами: make против new, append, nil-срезы и JSON. CX Codex +1 1 200установок migrate-to-shoehorn Matt Pocock Переводит type assertions с as в тестах на функции из @total-typescript/shoehorn. Нужен для частичных объектов и намеренно неверных данных в проверках. 475 388установок write-swift emilkowalski Скилл помогает писать, проверять и переносить код на Swift с учётом модели языка. Подойдёт, когда нужно разобраться с конкурентностью, ошибкой или циклом удержания объектов. CX Codex +1 119 300установок megacave JuliusBrussee Переводит ответы ассистента на классический китайский язык (вэньянь) для экономии места на экране. Активируется командами /megacave или /caveman wenyan. CX Codex +1 25 400установок find-docs upstash Тянет актуальную документацию, справочники API и примеры кода для любой библиотеки через Context7 CLI. Пригодится, когда агент отвечает по устаревшим данным обучения. CX Codex +1 9 400установок typescript-advanced-types Seth Hobson Помогает агенту писать сложную типизацию TypeScript: generics, conditional types и преобразования типов. Нужен для библиотек, API-клиентов и строгих конфигураций. CX Codex 92 169установок smart-explore thedotmack Структурно ищет функции и классы через tree-sitter. Пригодится, когда нужно разобраться в кодовой базе без чтения всех файлов. CX Codex +1 7 300установок

Из того же набора22

go-observability Скилл для Go-сервисов: помогает настроить структурные логи на log/slog, трейсы и метрики через OpenTelemetry, а также алерты по SLO. Пригодится, когда сервис уже в проде и нужно видеть, что в нём происходит. CX Codex +1 ★ 83звёзд репо go-concurrency-review Скилл проверяет конкурентный код на Go: жизненный цикл горутин, каналы, общие данные и передачу контекста. Пригодится для ревью, поиска гонок и проектирования конвейеров. CX Codex +1 ★ 83звёзд репо go-modernize Скилл помогает применять современные возможности Go и стандартной библиотеки. Пригодится для точечных правок или модернизации пакета и модуля. CX Codex +1 ★ 83звёзд репо go-error-handling Скилл задаёт агенту правила работы с ошибками в Go: обёртка через %w, sentinel-ошибки, свои типы и errors.Is/errors.As. CX Codex +1 ★ 83звёзд репо go-context Скилл для ИИ-агента, который проверяет и правит работу с context.Context в Go: отмена, таймауты, значения, типичные ошибки. CX Codex +1 ★ 83звёзд репо go-code-review Скилл проверяет Go-код и PR по структурированному списку: от обработки ошибок до тестов. Запускайте его перед слиянием изменений или для ревью пакета. CX Codex +1 ★ 83звёзд репо go-project-layout Подсказывает, как разложить новый Go-проект по папкам: cmd/, internal/, плоская раскладка для мелких утилит. Пригодится в самом начале, когда структура ещё не сложилась. CX Codex +1 ★ 83звёзд репо go-interface-design Скилл помогает проектировать интерфейсы Go, разделять зависимости и проверять контракты на этапе компиляции. Пригодится при рефакторинге и подготовке к тестированию. CX Codex +1 ★ 83звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой