정보
이 스킬은 nil 인터페이스, 슬라이스 앨리어싱, 정수 오버플로우와 같은 Go 코드에서 흔히 발생하는 문제들을 해결함으로써 개발자들이 런타임 오류와 미묘한 버그를 예방하도록 돕습니다. 코드 충돌 방지, nil 안전성 보장, API 경계에서의 방어적 결정 수립을 위해 사용됩니다. 이 가이드는 부동소수점 비교, 루프 내 defer 사용, 제로 값 설계와 같은 구체적인 패턴을 다루지만, 동시성, 보안 및 장애 발생 후 문제 해결은 포함하지 않습니다.
빠른 설치
Claude Code
추천npx skills add eduardo-sl/go-agent-skills -a claude-code/plugin add https://github.com/eduardo-sl/go-agent-skillsgit clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-defensive-codingClaude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요
문서
Go Defensive Coding
Go has no exceptions and no null-safety in the type system. Every trap below compiles cleanly, passes review, and fails in production.
Detailed reference material, loaded on demand:
references/nil-and-aliasing.md— the full typed-nil rules, slice aliasing scenarios, and memory retention.references/numeric-safety.md— conversion range checks, overflow detection, float and time comparison.
Read a reference file only when the section below is not enough.
Operating Modes
- Harden — you are writing or changing code. Apply every rule as you go.
- Review — you are auditing existing code. Report findings with severity (🔴 panic or corruption, 🟡 latent bug, 🟢 style) and cite file:line.
1. The Typed-Nil Interface Trap
A non-nil interface can hold a nil pointer. This is the single most common source of "impossible" nil checks in Go.
type NotFoundError struct{ ID string }
func (e *NotFoundError) Error() string { return "not found: " + e.ID }
// ❌ Bad — returns a non-nil error even on success
func find(id string) error {
var err *NotFoundError // typed nil
if id == "" {
err = &NotFoundError{ID: id}
}
return err // interface is (type=*NotFoundError, value=nil) — NOT nil
}
// ✅ Good — return the untyped nil literal
func find(id string) error {
if id == "" {
return &NotFoundError{ID: id}
}
return nil
}
Rules:
- Never declare a concrete error/pointer variable and return it as an
interface. Return
nilexplicitly on the success path. - Never store a possibly-nil concrete pointer in an
error,io.Reader, or any interface-typed struct field. go vet'snilnessanalyzer catches some of these. It does not catch all.
2. Nil Map, Slice, and Channel Behaviour
Memorise this table — half of these are safe and half panic or hang.
| Operation | nil map | nil slice | nil channel |
|---|---|---|---|
| Read / receive | zero value | index panics | blocks forever |
| Write / send | panics | append works | blocks forever |
len / cap | 0 | 0 | 0 |
range | zero iterations | zero iterations | blocks forever |
close | n/a | n/a | panics |
// ✅ A nil slice is a valid empty slice — do not guard append
var out []string
out = append(out, "a")
// ❌ A nil map is read-only
var m map[string]int
m["k"] = 1 // panic: assignment to entry in nil map
// ✅ Initialise every map before writing
m := make(map[string]int)
Return nil slices, not []T{}. They marshal identically in JSON for
encoding/json when the field is omitempty, and cost no allocation.
Return an empty non-nil map only when the caller is documented to write to it.
3. Slice Aliasing
A slice is a view. append writes through that view whenever capacity
allows, mutating data the caller still owns.
a := []int{1, 2, 3, 4}
b := a[:2]
b = append(b, 99) // ❌ overwrites a[2]; a is now [1 2 99 4]
// ✅ Full slice expression caps the view — append must reallocate
b := a[:2:2]
b = append(b, 99) // a is untouched
Apply this whenever you hand a subslice to code you do not control, and whenever a struct field holds a subslice of a larger buffer.
A subslice also keeps the entire backing array alive. To release a large
buffer, copy what you need: head := slices.Clone(buf[:64]).
4. Defensive Copying at Boundaries
Slices and maps are reference types. Storing or returning one without a copy hands out a mutable handle to your internals.
type Config struct{ hosts []string }
// ❌ Bad — caller can mutate our state, both ways
func NewConfig(hosts []string) *Config { return &Config{hosts: hosts} }
func (c *Config) Hosts() []string { return c.hosts }
// ✅ Good — copy in, copy out
func NewConfig(hosts []string) *Config {
return &Config{hosts: slices.Clone(hosts)}
}
func (c *Config) Hosts() []string { return slices.Clone(c.hosts) }
Use maps.Clone for maps. Both are shallow — a []*User clone still shares
the pointed-to users.
Copy when the value is retained past the call or exposed to a caller. Do not copy a slice you only read inside the function; that is wasted allocation.
Preventing accidental copies
A struct containing a sync.Mutex, sync.WaitGroup, or atomic.Int64 must
never be copied — the copy gets its own independent lock, and both halves
believe they are synchronised.
// ❌ Bad — the receiver is a copy, so the mutex protects nothing
func (c Counter) Value() int { ... }
// ❌ Bad — passing by value copies the mutex
func report(c Counter) { ... }
go vet's copylocks analyzer catches these. For types that must not be
copied but hold no lock, embed a noCopy marker so vet catches them too:
type noCopy struct{}
func (*noCopy) Lock() {}
func (*noCopy) Unlock() {}
type Tracker struct {
noCopy noCopy
// ...
}
5. Numeric Conversion and Comparison
Go never panics on numeric conversion. It truncates.
// ❌ Silent corruption when the value does not fit
count := int32(int64Total)
// ✅ Range-check before narrowing
if int64Total > math.MaxInt32 || int64Total < math.MinInt32 {
return fmt.Errorf("total %d out of int32 range", int64Total)
}
count := int32(int64Total)
The same applies to int → uint (negatives wrap to huge values) and to
len() results assigned to sized types. gosec reports these as G115.
Never compare floats with ==; never compare time.Time with ==.
// ✅ Floats: compare against a tolerance
if math.Abs(got-want) < 1e-9 { ... }
// ✅ Times: Equal compares the instant, == also compares wall clock and location
if t1.Equal(t2) { ... }
Integer division by zero panics; float division by zero yields ±Inf or
NaN, and NaN != NaN. Guard divisors that come from input.
6. Resource Lifecycle
defer runs at function return, not at the end of the block.
// ❌ Bad — all files stay open until the loop finishes
for _, name := range names {
f, err := os.Open(name)
if err != nil {
return err
}
defer f.Close()
process(f)
}
// ✅ Good — a function scope per iteration
for _, name := range names {
if err := func() error {
f, err := os.Open(name)
if err != nil {
return err
}
defer f.Close()
return process(f)
}(); err != nil {
return err
}
}
The same rule applies to resp.Body.Close, rows.Close, mu.Unlock, and
tx.Rollback inside loops or long-lived functions.
Check the error from a deferred Close on anything you wrote to — a failed
flush on close is a silent data loss otherwise:
defer func() {
if cerr := f.Close(); cerr != nil && err == nil {
err = fmt.Errorf("close %s: %w", name, cerr)
}
}()
7. Zero-Value and Initialisation Safety
Design types so the zero value works, then no constructor can be forgotten.
// ✅ Usable zero value — sync.Mutex and the nil map read are both fine
type Counter struct {
mu sync.Mutex
n map[string]int
}
func (c *Counter) Inc(k string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.n == nil { // lazily initialise on first write
c.n = make(map[string]int)
}
c.n[k]++
}
When lazy init must happen exactly once and may race, use sync.Once.
Avoid init(). It runs before main, cannot fail cleanly, cannot be tested
in isolation, and its cross-file order depends on filenames. Use an explicit
New... constructor that returns an error.
Enforce with Tooling
Run these; do not rely on reading alone. Skip and note any tool that is not installed.
go vet ./... # includes the nilness analyzer
golangci-lint run # errcheck, bodyclose, makezero, sqlclosecheck
gosec -include=G115,G104,G601 ./... # integer overflow, unhandled errors
go test -race ./... # aliasing bugs often surface as races
Relevant golangci-lint linters: errcheck, bodyclose, sqlclosecheck,
rowserrcheck, makezero, nilerr, exhaustive, and govet with the
nilness analyzer enabled.
Go 1.22 and later give each loop iteration its own variable. Do not add the
old v := v shadow line; do not remove one from a module still on go 1.21.
Verification Checklist
- No function returns a concrete pointer type as an interface on a success path
- Every map is initialised before its first write
- Subslices handed across a package boundary use a full slice expression
a[:n:n] - Slices and maps stored in or returned from a struct are cloned
- No type holding a mutex or atomic is passed or received by value
- Every narrowing numeric conversion is range-checked, or documented as bounded
- No
==on floats or ontime.Time - Divisors derived from input are checked against zero
- No
deferinside a loop body without an enclosing function scope - Deferred
Closeon written resources reports its error go vet,golangci-lintandgo test -raceare clean
GitHub 저장소
자주 묻는 질문
go-defensive-coding Skill이란 무엇인가요?
go-defensive-coding은(는) eduardo-sl이(가) 만든 Claude Skill입니다. Skill은 Claude가 필요할 때 불러오는 지침과 리소스를 묶어 추가 프롬프트 없이 go-defensive-coding 관련 작업을 수행할 수 있게 합니다.
go-defensive-coding은(는) 어떻게 설치하나요?
이 페이지의 설치 명령을 사용하세요. go-defensive-coding을(를) Claude Code 플러그인으로 추가하거나 저장소를 skills 디렉터리에 복제한 다음 Claude를 다시 시작해 Skill을 불러옵니다.
go-defensive-coding은(는) 어떤 카테고리에 속하나요?
go-defensive-coding은(는) 디자인 카테고리에 속합니다.
go-defensive-coding은(는) 무료로 사용할 수 있나요?
네. go-defensive-coding은(는) AIMCP에 등록되어 있으며 무료로 설치할 수 있습니다.
연관 스킬
executing-plans 스킬은 검토 체크포인트가 포함된 통제된 배치로 실행할 완전한 구현 계획이 있을 때 사용합니다. 이 스킬은 계획을 불러와 비판적으로 검토한 후, 소규모 배치(기본값 3개 작업)로 작업을 실행하면서 각 배치 사이에 진행 상황을 아키텍트 검토를 위해 보고합니다. 이를 통해 내재된 품질 관리 체크포인트를 갖춘 체계적인 구현이 보장됩니다.
이 스킬은 코드 변경 사항을 요구 사항에 따라 분석하기 위해 코드 리뷰어 하위 에이전트를 호출합니다. 작업 완료 후, 주요 기능 구현 후, 또는 메인 브랜치에 병합하기 전에 사용해야 합니다. 이 리뷰는 현재 구현체와 원래 계획을 비교하여 문제를 조기에 발견하는 데 도움이 됩니다.
이 스킬은 개발자들이 HTTP, stdio 또는 SSE 전송 방식을 통해 MCP 서버를 Claude Code에 연결하는 포괄적인 가이드를 제공합니다. GitHub, Notion 및 사용자 정의 API와 같은 외부 서비스를 통합하기 위한 설치, 구성, 인증 및 보안을 다룹니다. MCP 통합 설정, 외부 도구 구성 또는 Claude의 모델 컨텍스트 프로토콜 작업 시 활용하세요.
이 스킬은 작업 분석을 기반으로 개발자가 Claude Code 웹 인터페이스와 CLI 인터페이스 중 선택할 수 있도록 돕고, 두 환경 간 원활한 세션 텔레포트를 가능하게 합니다. 웹, CLI 또는 모바일 환경 전환 시 세션 상태와 컨텍스트를 관리하여 워크플로를 최적화합니다. 다양한 단계에서 서로 다른 도구가 필요한 복잡한 프로젝트에 사용하세요.
