MCP HubMCP Hub
SKILL·E9C0E6

go-data-structures

eduardo-sl
更新日 27 days ago
4 閲覧
69
9
69
GitHubで表示
デザインaidesigndata

について

このスキルは、Goのコアデータ構造(スライス、マップ、配列)に関するベストプラクティスを提供し、nilと空スライスの違い、エイリアシング、事前割り当て、マップのイテレーションといった一般的な落とし穴をカバーします。スライスのセマンティクス、セットの実装、データ構造の選択に関する質問にご利用ください。並行処理、パフォーマンスプロファイリング、汎用設計のトピックは明示的に除外されており、これらは他のスキルで扱われています。

クイックインストール

Claude Code

推奨
メイン
npx skills add eduardo-sl/go-agent-skills -a claude-code
プラグインコマンド代替
/plugin add https://github.com/eduardo-sl/go-agent-skills
Git クローン代替
git clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-data-structures

このコマンドをClaude Codeにコピー&ペーストしてスキルをインストールします

ドキュメント

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.

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 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. nil marshals to null, empty marshals to []. If the API contract requires [], return an empty slice explicitly.
  • 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 = 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:

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

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.

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

GitHub リポジトリ

eduardo-sl/go-agent-skills
パス: skills/(code-quality)/go-data-structures
0
FAQ

よくある質問

go-data-structures Skillとは何ですか?

go-data-structures はeduardo-sl が作成した Claude Skillです。Skillは、Claudeが必要に応じて読み込む指示とリソースをまとめ、追加の指示なしで go-data-structures に関連するタスクを実行できるようにします。

go-data-structures をインストールするには?

このページのインストールコマンドを使用してください。go-data-structures をプラグインとして Claude Code に追加するか、リポジトリを skills ディレクトリにクローンし、Claudeを再起動してSkillを読み込みます。

go-data-structures はどのカテゴリに属しますか?

go-data-structures は デザイン カテゴリに属します。

go-data-structures は無料で利用できますか?

はい。go-data-structures は AIMCP に掲載されており、無料でインストールできます。

関連スキル

executing-plans
デザイン

executing-plansスキルは、完全な実装計画があり、それを管理されたバッチでレビューチェックポイントを設けながら実行する場合に使用します。このスキルは計画を読み込んで批判的にレビューした後、小さなバッチ(デフォルトは3タスク)でタスクを実行し、各バッチの間に進捗状況を報告してアーキテクトのレビューを受けます。これにより、品質管理チェックポイントが組み込まれた体系的な実装が保証されます。

スキルを見る
requesting-code-review
デザイン

このスキルは、コードレビュアーサブエージェントを起動し、処理を進める前に要件に対してコード変更を分析します。タスク完了後、主要な機能の実装後、またはmainブランチへのマージ前などに使用すべきです。このレビューは、現在の実装と元の計画を比較することで、問題を早期に発見するのに役立ちます。

スキルを見る
connect-mcp-server
デザイン

このスキルは、開発者がHTTP、stdio、またはSSEトランスポートを使用してMCPサーバーをClaude Codeに接続するための包括的なガイドを提供します。GitHub、Notion、カスタムAPIなどの外部サービスを統合するためのインストール、設定、認証、セキュリティについて解説しています。MCP統合のセットアップ、外部ツールの設定、またはClaudeのModel Context Protocolを扱う際にご利用ください。

スキルを見る
web-cli-teleport
デザイン

このスキルは、タスク分析に基づいて開発者がClaude Code WebとCLIインターフェースの選択を支援し、これらの環境間でのシームレスなセッションテレポーテーションを可能にします。Web、CLI、モバイル環境を切り替える際のセッション状態とコンテキストを管理することで、ワークフローを最適化します。様々な段階で異なるツールを必要とする複雑なプロジェクトにご活用ください。

スキルを見る