MCP HubMCP Hub
SKILL·E9C0E6

go-data-structures

eduardo-sl
업데이트됨 22 days ago
4 조회
68
9
68
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
디자인

이 스킬은 코드 변경 사항을 요구 사항에 따라 분석하기 위해 코드 리뷰어 하위 에이전트를 호출합니다. 작업 완료 후, 주요 기능 구현 후, 또는 메인 브랜치에 병합하기 전에 사용해야 합니다. 이 리뷰는 현재 구현체와 원래 계획을 비교하여 문제를 조기에 발견하는 데 도움이 됩니다.

스킬 보기
connect-mcp-server
디자인

이 스킬은 개발자들이 HTTP, stdio 또는 SSE 전송 방식을 통해 MCP 서버를 Claude Code에 연결하는 포괄적인 가이드를 제공합니다. GitHub, Notion 및 사용자 정의 API와 같은 외부 서비스를 통합하기 위한 설치, 구성, 인증 및 보안을 다룹니다. MCP 통합 설정, 외부 도구 구성 또는 Claude의 모델 컨텍스트 프로토콜 작업 시 활용하세요.

스킬 보기
web-cli-teleport
디자인

이 스킬은 작업 분석을 기반으로 개발자가 Claude Code 웹 인터페이스와 CLI 인터페이스 중 선택할 수 있도록 돕고, 두 환경 간 원활한 세션 텔레포트를 가능하게 합니다. 웹, CLI 또는 모바일 환경 전환 시 세션 상태와 컨텍스트를 관리하여 워크플로를 최적화합니다. 다양한 단계에서 서로 다른 도구가 필요한 복잡한 프로젝트에 사용하세요.

스킬 보기