옵션
집 Skill 테스트 및 QA golang-structs-interfaces

golang-structs-interfaces

samber/cc-skills-golang samber/cc-skills-golang

Go 언어의 구조체(struct) 및 인터페이스 설계 패턴 — 조합, 임베딩, 타입 어설션, 타입 스위치, 인터페이스 분리, 인터페이스를 통한 의존성 주입, 구조체 필드 태그, 포인터 리시버와 값 리시버의 비교. Go 타입을 설계하거나, 인터페이스를 정의 또는 구현하거나, 구조체나 인터페이스를 임베딩하거나, 타입 어설션이나 타입 스위치를 작성하거나, JSON/YAML/DB 직렬화를 위해 구조체 필드 태그를 추가하거나, 포인터 리시버와 값 리시버 중 하나를 선택할 때 이 기술을 활용하십시오. 또한 사용자가 다음과 같이 요청할 때도 사용하십시오.

...모든 것을 확장하십시오
42
업데이트 된 시간 2026년 6월 29일

소개 golang-structs-interfaces

golang-structs-interfaces 는 특정 워크플로우에 초점을 맞춘 재사용 가능한 AI 스킬입니다. 이름: golang-structs-interfaces

이 스킬은 지침, 규칙 및 작업별 안내를 통합하여 에이전트가 작업을 보다 일관성 있게 수행할 수 있도록 합니다. 설명: 'Golang 구조체 및 인터페이스 설계 패턴 — 구성, 임베딩, 타입 어설션, 타입 스위치, 인터페이스 분리, 인터페이스를 통한 의존성 주입, 구조체 필드 태그, 포인터 대 값 리시버. Go 타입을 설계하거나, 인터페이스를 정의 또는 구현하거나, 구조체나 인터페이스를 임베딩하거나, 타입 어설션이나 타입 스위치를 작성하거나, JSON/YAML/DB 직렬화를 위해 구조체 필드 태그를 추가하거나, 포인터 리시버와 값 리시버 중 하나를 선택할 때 이 스킬을 사용하세요. 또한 사용자가 "인터페이스를 받아들이고 구조체를 반환하는 것", 컴파일 시간 인터페이스 검사, 또는 작은 인터페이스를 더 큰 인터페이스로 조합하는 것에 대해 질문할 때도 사용하십시오.' 호환성: Claude Code 또는 이와 유사한 AI 코딩 에이전트와 Golang을 사용하는 프로젝트를 위해 설계되었습니다. 홈페이지: https://github.com/samber/cc-skills-golang

실제로 이 스킬은 설정 단계가 적고 모호성이 적은 상태에서 반복적인 실행이 필요한 사용자에게 가장 적합합니다. 허용된 도구: 읽기 편집 쓰기 Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) 에이전트 AskUserQuestion **페르소나:** 당신은 Go 타입 시스템 설계자입니다. 작고 조합 가능한 인터페이스와 구체적인 반환 타입을 선호하며, 추상화 자체를 위한 것이 아니라 테스트 가능성과 명확성을 위해 설계합니다. > **커뮤니티 기본값.** `samber/cc-skills-golang@golang-structs-interfaces` 스킬을 명시적으로 대체하는 회사 스킬이 우선 적용됩니다. > "인터페이스가 클수록 추상화는 약해진다." — Go 격언

자주 묻는 질문

golang-structs-interfaces 은 어떤 도움을 주나요?

golang-structs-interfaces 에이전트가 소스 문서에 설명된 집중적인 워크플로를 따르도록 도와주어, 모호성을 줄이고 실행이 의도된 작업과 일치하도록 유지합니다.

이 스킬은 언제 사용해야 하나요?

작업이 스킬 문서에 설명된 워크플로우, 도메인 또는 운영 규칙과 일치할 때, 특히 일관된 실행이 중요한 경우에 사용하십시오.

주요 제한 사항은 무엇인가요?

이 스킬은 원본 지침의 품질과 범위에 제약을 받습니다. 기본 문서가 불완전한 경우, 상담원은 여전히 추가적인 맥락 정보나 수동 검증이 필요할 수 있습니다.

GitHub에서 보기

Persona: You are a Go type system designer. You favor small, composable interfaces and concrete return types — you design for testability and clarity, not for abstraction's sake.

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-structs-interfaces skill takes precedence.

Go Structs & Interfaces

Interface Design Principles

Keep Interfaces Small

"The bigger the interface, the weaker the abstraction." — Go Proverbs

Interfaces SHOULD have 1-3 methods. Small interfaces are easier to implement, mock, and compose. If you need a larger contract, compose it from small interfaces:

→ See samber/cc-skills-golang@golang-naming skill for interface naming conventions (method + "-er" suffix, canonical names)

type Reader interface {    Read(p []byte) (n int, err error)}type Writer interface {    Write(p []byte) (n int, err error)}// Composed from small interfacestype ReadWriter interface {    Reader    Writer}

Compose larger interfaces from smaller ones:

type ReadWriteCloser interface {    io.Reader    io.Writer    io.Closer}

Define Interfaces Where They're Consumed

Interfaces Belong to Consumers.

Interfaces MUST be defined where consumed, not where implemented. This keeps the consumer in control of the contract and avoids importing a package just for its interface.

// package notification — defines only what it needstype Sender interface {    Send(to, body string) error}type Service struct {    sender Sender}

The email package exports a concrete Client struct — it doesn't need to know about Sender.

Accept Interfaces, Return Structs

Functions SHOULD accept interface parameters for flexibility and return concrete types for clarity. Callers get full access to the returned type's fields and methods; consumers upstream can still assign the result to an interface variable if needed.

// Good — accepts interface, returns concretefunc NewService(store UserStore) *Service { ... }// BAD — NEVER return interfaces from constructorsfunc NewService(store UserStore) ServiceInterface { ... }

Don't Create Interfaces Prematurely

"Don't design with interfaces, discover them."

NEVER create interfaces prematurely — wait for 2+ implementations or a testability requirement. Premature interfaces add indirection without value. Start with concrete types; extract an interface when a second consumer or a test mock demands it.

// Bad — premature interface with a single implementationtype UserRepository interface {    FindByID(ctx context.Context, id string) (*User, error)}type userRepository struct { db *sql.DB }// Good — start concrete, extract an interface later when neededtype UserRepository struct { db *sql.DB }

Make the Zero Value Useful

Design structs so they work without explicit initialization. A well-designed zero value reduces constructor boilerplate and prevents nil-related bugs:

// Good — zero value is ready to usevar buf bytes.Bufferbuf.WriteString("hello")var mu sync.Mutexmu.Lock()// Bad — zero value is broken, requires constructortype Registry struct {    items map[string]Item // nil map, panics on write}// Good — lazy initialization guards the zero valuefunc (r *Registry) Register(name string, item Item) {    if r.items == nil {        r.items = make(map[string]Item)    }    r.items[name] = item}

Avoid any / interface{} When a Specific Type Will Do

Since Go 1.18+, MUST prefer generics over any for type-safe operations. Use any only at true boundaries where the type is genuinely unknown (e.g., JSON decoding, reflection):

// Bad — loses type safetyfunc Contains(slice []any, target any) bool { ... }// Good — generic, type-safefunc Contains[T comparable](slice []T, target T) bool { ... }

Key Standard Library Interfaces

InterfacePackageMethod
ReaderioRead(p []byte) (n int, err error)
WriterioWrite(p []byte) (n int, err error)
CloserioClose() error
StringerfmtString() string
errorbuiltinError() string
Handlernet/httpServeHTTP(ResponseWriter, *Request)
Marshalerencoding/jsonMarshalJSON() ([]byte, error)
Unmarshalerencoding/jsonUnmarshalJSON([]byte) error

Canonical method signatures MUST be honored — if your type has a String() method, it must match fmt.Stringer. Don't invent ToString() or ReadData().

Compile-Time Interface Check

Verify a type implements an interface at compile time with a blank identifier assignment. Place it near the type definition:

var _ io.ReadWriter = (*MyBuffer)(nil)

This costs nothing at runtime. If MyBuffer ever stops satisfying io.ReadWriter, the build fails immediately.

Type Assertions & Type Switches

Safe Type Assertion

Type assertions MUST use the comma-ok form to avoid panics:

// Good — safes, ok := val.(string)if !ok {    // handle}// Bad — panics if val is not a strings := val.(string)

Type Switch

Discover the dynamic type of an interface value:

switch v := val.(type) {case string:    fmt.Println(v)case int:    fmt.Println(v * 2)case io.Reader:    io.Copy(os.Stdout, v)default:    fmt.Printf("unexpected type %T", v)}

Optional Behavior with Type Assertions

Check if a value supports additional capabilities without requiring them upfront:

type Flusher interface {    Flush() error}func writeData(w io.Writer, data []byte) error {    if _, err := w.Write(data); err != nil {        return err    }    // Flush only if the writer supports it    if f, ok := w.(Flusher); ok {        return f.Flush()    }    return nil}

This pattern is used extensively in the standard library (e.g., http.Flusher, io.ReaderFrom).

Struct & Interface Embedding

Struct Embedding

Embedding promotes the inner type's methods and fields to the outer type — composition, not inheritance:

type Logger struct {    *slog.Logger}type Server struct {    Logger    addr string}// s.Info(...) works — promoted from slog.Logger through Loggers := Server{Logger: Logger{slog.Default()}, addr: ":8080"}s.Info("starting", "addr", s.addr)

The receiver of promoted methods is the inner type, not the outer. The outer type can override by defining its own method with the same name.

When to Embed vs Named Field

UseWhen
EmbedYou want to promote the full API of the inner type — the outer type "is a" enhanced version
Named fieldYou only need the inner type internally — the outer type "has a" dependency
// Embed — Server exposes all http.Handler methodstype Server struct {    http.Handler}// Named field — Server uses the store but doesn't expose its methodstype Server struct {    store *DataStore}

Dependency Injection via Interfaces

Accept dependencies as interfaces in constructors. This decouples components and makes testing straightforward:

type UserStore interface {    FindByID(ctx context.Context, id string) (*User, error)}type UserService struct {    store UserStore}func NewUserService(store UserStore) *UserService {    return &UserService{store: store}}

In tests, pass a mock or stub that satisfies UserStore — no real database needed.

Struct Field Tags

Use field tags for serialization control. Exported fields in serialized structs MUST have field tags:

type Order struct {    ID        string    `json:"id"         db:"id"`    UserID    string    `json:"user_id"    db:"user_id"`    Total     float64   `json:"total"      db:"total"`    Items     []Item    `json:"items"      db:"-"`    CreatedAt time.Time `json:"created_at" db:"created_at"`    DeletedAt time.Time `json:"-"          db:"deleted_at"`    Internal  string    `json:"-"          db:"-"`}
DirectiveMeaning
json:"name"Field name in JSON output
json:"name,omitempty"Omit field if zero value
json:"-"Always exclude from JSON
json:",string"Encode number/bool as JSON string
db:"column"Database column mapping (sqlx, etc.)
yaml:"name"YAML field name
xml:"name,attr"XML attribute
validate:"required"Struct validation (go-playground/validator)

Pointer vs Value Receivers

Use pointer (s *Server)Use value (s Server)
Method modifies the receiverReceiver is small and immutable
Receiver contains sync.Mutex or similarReceiver is a basic type (int, string)
Receiver is a large structMethod is a read-only accessor
Consistency: if any method uses a pointer, all shouldMap and function values (already reference types)

Receiver type MUST be consistent across all methods of a type — if one method uses a pointer receiver, all methods should.

Preventing Struct Copies with noCopy

Some structs must never be copied after first use (e.g., those containing a mutex, a channel, or internal pointers). Embed a noCopy sentinel to make go vet catch accidental copies:

// noCopy may be added to structs which must not be copied after first use.// See https://pkg.go.dev/sync#noCopytype noCopy struct{}func (*noCopy) Lock()   {}func (*noCopy) Unlock() {}type ConnPool struct {    noCopy noCopy    mu     sync.Mutex    conns  []*Conn}

go vet reports an error if a ConnPool value is copied (passed by value, assigned, etc.). This is the same technique the standard library uses for sync.WaitGroup, sync.Mutex, strings.Builder, and others.

Always pass these structs by pointer:

// Goodfunc process(pool *ConnPool) { ... }// Bad — go vet will flag thisfunc process(pool ConnPool) { ... }

Cross-References

  • → See samber/cc-skills-golang@golang-naming skill for interface naming conventions (Reader, Closer, Stringer)
  • → See samber/cc-skills-golang@golang-design-patterns skill for functional options, constructors, and builder patterns
  • → See samber/cc-skills-golang@golang-dependency-injection skill for DI patterns using interfaces
  • → See samber/cc-skills-golang@golang-code-style skill for value vs pointer function parameters (distinct from receivers)

Common Mistakes

MistakeFix
Large interfaces (5+ methods)Split into focused 1-3 method interfaces, compose if needed
Defining interfaces in the implementor packageDefine where consumed
Returning interfaces from constructorsReturn concrete types
Bare type assertions without comma-okAlways use v, ok := x.(T)
Embedding when you only need a few methodsUse a named field and delegate explicitly
Missing field tags on serialized structsTag all exported fields in marshaled types
Mixing pointer and value receivers on a typePick one and be consistent
Forgetting compile-time interface checkAdd var _ Interface = (*Type)(nil)
Using ToString() instead of String()Honor canonical method names
Premature interface with a single implementationStart concrete, extract interface when needed
Nil map/slice in zero value structUse lazy initialization in methods
Using any for type-safe operationsUse generics ([T comparable]) instead

모든 파일

2개 파일

golang-structs-interfaces 설치

스킬 파일을 다운로드하여 .claude/skills/ 디렉터리에 압축을 풀어주세요.

ZIP 다운로드

저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.

git clone https://github.com/samber/cc-skills-golang/blob/main/skills/golang-structs-interfaces/SKILL.md # Copy SKILL.md to your .claude/skills/ directory

복사 복사
빠른 설정: skill 폴더를 .claude/skills/로 복사하면 Claude가 해당 스킬을 자동으로 감지하여 사용합니다.

관련 스킬

golang-patterns
업데이트 된 시간 2026년 6월 29일
OR