golang-structs-interfaces

bởi samber

Các mẫu thiết kế struct và interface trong Golang — composition, embedding, type assertions, type switches, phân tách interface, dependency injection qua interface, thẻ trường struct, và receiver con trỏ so với receiver giá trị. Sử dụng kỹ năng này khi thiết kế các kiểu Go, định nghĩa hoặc triển khai interface, nhúng struct hoặc interface, viết type assertions hoặc type switches, thêm thẻ trường struct cho serialization JSON/YAML/DB, hoặc chọn giữa receiver con trỏ và receiver giá trị. Cũng sử dụng khi người dùng...

npx skills add https://github.com/samber/cc-skills-golang --skill golang-structs-interfaces

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 interfaces
type 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 needs
type 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 concrete
func NewService(store UserStore) *Service { ... }

// BAD — NEVER return interfaces from constructors
func 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 implementation
type UserRepository interface {
    FindByID(ctx context.Context, id string) (*User, error)
}
type userRepository struct { db *sql.DB }

// Good — start concrete, extract an interface later when needed
type 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 use
var buf bytes.Buffer
buf.WriteString("hello")

var mu sync.Mutex
mu.Lock()

// Bad — zero value is broken, requires constructor
type Registry struct {
    items map[string]Item // nil map, panics on write
}

// Good — lazy initialization guards the zero value
func (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 safety
func Contains(slice []any, target any) bool { ... }

// Good — generic, type-safe
func 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 — safe
s, ok := val.(string)
if !ok {
    // handle
}

// Bad — panics if val is not a string
s := 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\n", 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 Logger
s := 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 methods
type Server struct {
    http.Handler
}

// Named field — Server uses the store but doesn't expose its methods
type 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#noCopy
type 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:

// Good
func process(pool *ConnPool) { ... }

// Bad — go vet will flag this
func 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

Thêm skills từ samber

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
Các mẫu thiết kế Golang theo phong cách bản địa — tùy chọn hàm, hàm khởi tạo, luồng lỗi và xếp tầng, quản lý tài nguyên và vòng đời, tắt máy an toàn, khả năng phục hồi, kiến trúc, tiêm phụ thuộc, xử lý dữ liệu, truyền phát, v.v. Áp dụng khi lựa chọn rõ ràng giữa các mẫu kiến trúc, triển khai tùy chọn hàm, thiết kế API hàm khởi tạo, thiết lập tắt máy an toàn, áp dụng các mẫu phục hồi, hoặc hỏi mẫu Go bản địa nào phù hợp với một vấn đề cụ thể.
developmentdesigncode-review
golang-error-handling
samber
Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops`...
developmentcode-review
golang-performance
samber
Các mẫu và phương pháp tối ưu hiệu năng Golang - nếu X là điểm nghẽn, thì áp dụng Y. Bao gồm giảm cấp phát, hiệu quả CPU, bố trí bộ nhớ, tinh chỉnh GC, pooling, caching, và tối ưu đường dẫn nóng. Sử dụng khi profiling hoặc benchmark đã xác định được điểm nghẽn và bạn cần mẫu tối ưu phù hợp để khắc phục. Cũng sử dụng khi thực hiện đánh giá mã hiệu năng để đề xuất cải tiến hoặc benchmark có thể giúp xác định các cải thiện hiệu năng nhanh chóng. Không dành cho phương pháp đo lường (→...
developmentcode-review
golang-security
samber
Các phương pháp bảo mật tốt nhất và phòng ngừa lỗ hổng cho Golang. Bao gồm injection (SQL, lệnh, XSS), mật mã học, an toàn hệ thống tệp, bảo mật mạng, cookie, quản lý bí mật, an toàn bộ nhớ và ghi nhật ký. Áp dụng khi viết, xem xét hoặc kiểm tra mã Go về bảo mật, hoặc khi làm việc trên bất kỳ mã rủi ro nào liên quan đến mật mã, I/O, quản lý bí mật, xử lý đầu vào người dùng hoặc xác thực. Bao gồm cấu hình các công cụ bảo mật.
securitycode-reviewdevelopment
golang-database
samber
Hướng dẫn toàn diện về truy cập cơ sở dữ liệu Go — truy vấn tham số hóa, quét struct, cột NULL, giao dịch, mức cô lập, SELECT FOR UPDATE, connection pool, xử lý hàng loạt, truyền context và công cụ migration. Sử dụng khi viết, xem xét hoặc gỡ lỗi mã Golang tương tác với PostgreSQL, MariaDB, MySQL hoặc SQLite; để kiểm thử cơ sở dữ liệu; hoặc cho các câu hỏi về database/sql, sqlx hoặc pgx. KHÔNG tạo lược đồ cơ sở dữ liệu hoặc SQL migration.
developmentdatabase
golang-lint
samber
Các phương pháp linting tốt nhất và cấu hình golangci-lint cho các dự án Golang — chạy linters, cấu hình .golangci.yml, loại bỏ cảnh báo bằng chỉ thị nolint, diễn giải đầu ra lint, và lựa chọn linters. Sử dụng khi cấu hình golangci-lint, hỏi về cảnh báo lint hoặc loại bỏ nolint, thiết lập công cụ chất lượng mã, hoặc chọn linters. Cũng sử dụng khi người dùng đề cập đến golangci-lint, go vet, staticcheck, hoặc revive.
developmentcode-reviewtesting