選項
首頁首頁 Skill 測試和品質保證 golang-structs-interfaces

golang-structs-interfaces

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

Go 語言的結構體與介面設計模式 — 組合、嵌入、類型斷言、類型切換、介面分離、透過介面進行依賴注入、結構體欄位標籤,以及指標接收器與值接收器的比較。 在設計 Go 類型、定義或實作介面、嵌入結構體或介面、撰寫類型斷言或類型切換、為 JSON/YAML/資料庫序列化新增結構體欄位標籤,或選擇指標接收器與值接收器時,皆可運用此技能。此外,當使用者詢問

...展開全部
42
更新時間 2026-06-29

關於golang-structs-interfaces

golang-structs-interfaces 這是一項專注於特定工作流程的可重複使用 AI 技能。名稱:golang-structs-interfaces

此技能整合了操作指示、規範及任務專屬指引,使代理程式能更一致地執行工作。描述:'Golang 結構體與介面設計模式 — 組合、嵌入、類型斷言、類型切換、介面分離、透過介面進行依賴注入、結構體欄位標籤,以及指標與值接收器的區別。 在設計 Go 類型、定義或實作介面、嵌入結構體或介面、撰寫類型斷言或類型切換、為 JSON/YAML/資料庫序列化新增結構體欄位標籤,或選擇指標與值接收器時,請使用此技能。 此外,當使用者詢問「接受介面、回傳結構體」、編譯時介面檢查,或將小型介面組合成較大型介面時,亦可使用此技能。」相容性:專為 Claude Code 或類似的 AI 程式設計代理設計,並適用於使用 Golang 的專案。首頁:https://github.com/samber/cc-skills-golang

實際上,這項技能最適合需要可重複執行、且設定步驟較少、模糊性較低的使用者。允許的工具:讀取 編輯 寫入 Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) 代理 詢問使用者問題 **角色設定:** 您是一位 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

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/,Claude 會自動偵測並使用該技能

相關技能

golang-patterns
更新時間 2026-06-29
OR