跳至正文
OpenAgentSkill
浏览已开放 · 目录记录日期 2026-11-21 · 自动更新和账户服务暂时关闭。
开发与测试

go-functions-methods

Enforces best practices for Go functions and methods including receiver type selection, named result parameters, nil receiver pitfalls, io.Reader over filenames, and defer argument evaluation. Use when writing, reviewing, or refactoring Go functions, methods, receivers, or defer statements.

v0lka · 已有静态检查记录

安装与使用

运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。

npx skills add v0lka/skills --skill go-functions-methods

技能说明


name: go-functions-methods description: Enforces best practices for Go functions and methods including receiver type selection, named result parameters, nil receiver pitfalls, io.Reader over filenames, and defer argument evaluation. Use when writing, reviewing, or refactoring Go functions, methods, receivers, or defer statements.

Go Functions & Methods

Rules for writing correct Go functions and methods, covering receiver types, named results, nil receivers, function inputs, and defer evaluation.

Receiver Type Selection

Must use pointer receiver when:

  • The method mutates the receiver
  • The receiver contains a non-copyable field (e.g., sync.Mutex, sync.WaitGroup)
// Mutating a slice receiver requires a pointer
type slice []int

func (s *slice) add(element int) {
    *s = append(*s, element)
}

Should use pointer receiver when:

  • The receiver is a large struct (benchmark if unsure)

Must use value receiver when:

  • The receiver is a map, function, or channel (compiler error otherwise)
  • You need to enforce immutability of the receiver

Should use value receiver when:

  • The receiver is a small, naturally value-like struct with no mutable fields (e.g., time.Time)
  • The receiver is a slice that the method does not mutate
  • The receiver is a basic type (int, float64, string)

Default rule

Choose a value receiver unless there is a specific reason to use a pointer. When in doubt, prefer a pointer receiver.

Mixing receiver types

Avoid mixing value and pointer receivers on the same type. Exception: when a value-semantic type must implement an interface that requires mutation (e.g., time.Time uses value receivers everywhere except UnmarshalBinary which requires a pointer to satisfy encoding.TextUnmarshaler).

Indirect mutation through pointer fields

A value receiver can still mutate data reachable through pointer fields. For clarity, use a pointer receiver to signal that the type is mutable:

type customer struct {
    data *data // pointer field
}

// Even though this compiles with a value receiver and mutates
// data.balance, prefer a pointer receiver for clarity:
func (c *customer) add(amount float64) {
    c.data.balance += amount
}

Named Result Parameters

When to use

  • In interface definitions where multiple results of the same type would be ambiguous:
// Bad - which float32 is latitude vs longitude?
type locator interface {
    getCoordinates(address string) (float32, float32, error)
}

// Good - self-documenting
type locator interface {
    getCoordinates(address string) (lat, lng float32, err error)
}
  • In implementations where naming improves clarity for same-type returns
  • When zero-value initialization makes the implementation shorter (e.g., io.ReadFull pattern)

When NOT to use

  • When the return type is already unambiguous (e.g., a single error return)
// Unnecessary - naming err adds nothing
func StoreCustomer(customer Customer) (err error) { ... }

// Prefer
func StoreCustomer(customer Customer) error { ... }

Naked returns

  • Only acceptable in short functions
  • Never mix naked returns and explicit returns within the same function
  • Named result parameters do not require naked returns -- you can name them for clarity and still use explicit returns

Unintended Side Effects with Named Result Parameters

Named result parameters are initialized to their zero value. This can silently produce nil errors.

// BUG: if ctx.Err() != nil, this returns err which is still nil!
func (l loc) getCoordinates(ctx context.Context, address string) (
    lat, lng float32, err error) {
    isValid := l.validateAddress(address)
    if !isValid {
        return 0, 0, errors.New("invalid address")
    }
    if ctx.Err() != nil {
        return 0, 0, err // err is still nil here!
    }
    // ...
}

Fix: always assign to the named variable before returning it:

if err = ctx.Err(); err != nil {
    return 0, 0, err
}

Rule: When reviewing code with named result parameters, verify that every return path either assigns the named variable or uses an explicit value. Watch for returns that reference a named error variable that was never assigned.

Returning a Nil Receiver (nil Pointer vs nil Interface)

A nil pointer converted to an interface produces a non-nil interface value. The interface wrapper is non-nil even though the wrapped pointer is nil.

type MultiError struct {
    errs []string
}

func (m *MultiError) Error() string {
    return strings.Join(m.errs, ";")
}

// BUG: always returns non-nil error even when valid
func (c Customer) Validate() error {
    var m *MultiError
    if c.Age < 0 {
        m = &MultiError{}
        m.Add(errors.New("age is negative"))
    }
    if c.Name == "" {
        if m == nil {
            m = &MultiError{}
        }
        m.Add(errors.New("name is nil"))
    }
    return m // m is a nil *MultiError, but wrapping it in error makes it non-nil!
}

Fix: return nil explicitly when there is no error:

func (c Customer) Validate() error {
    var m *MultiError
    // ... same validation logic ...

    if m != nil {
        return m
    }
    return nil // explicit nil interface, not a nil pointer cast to interface
}

Rule: When a function returns an interface type and builds the concrete value conditionally, never return the concrete pointer variable directly at the end. Check for nil and return a nil literal. This applies to any interface, not just error.

Accept io.Reader, Not Filenames

Functions that accept a filename to read from are a code smell. They are hard to test (require creating files) and not reusable across data sources.

// Bad - tied to filesystem, hard to test
func countEmptyLines(filename string) (int, error) {
    file, err := os.Open(filename)
    // ...
}

// Good - works with files, HTTP bodies, strings, etc.
func countEmptyLines(reader io.Rea
阅读完整来源 ↗