accept-interfaces-return-structs

Core pattern for flexible, testable Go APIs

⭐2stars🔀0forks📁View on GitHub🕐Updated Dec 28, 2025

When & Why to Use This Skill

This Claude skill provides a comprehensive guide and implementation pattern for the 'Accept Interfaces, Return Structs' principle in Go. It helps developers design flexible, decoupled, and highly testable APIs by ensuring functions depend on abstractions for inputs while providing concrete, discoverable types for outputs.

Use Cases

  • Unit Testing and Mocking: Easily swap real dependencies with mock implementations by designing functions that accept interfaces, facilitating isolated and reliable tests.
  • API Evolution and Compatibility: Return concrete structs to allow the addition of new methods in the future without breaking existing interface contracts or caller expectations.
  • Reducing Package Coupling: Prevent tight coupling and circular dependencies between Go packages by defining interfaces at the consumer side rather than the producer side.
  • Improving Code Discoverability: Ensure that all methods of a returned object are visible and accessible to the caller without unnecessary interface casting.
nameaccept-interfaces-return-structs
descriptionCore pattern for flexible, testable Go APIs

Accept Interfaces, Return Structs

The fundamental Go interface design principle: functions should accept interfaces but return concrete types.

The Pattern

CORRECT - Accept interface, return concrete

type Storage interface {
    Save(data []byte) error
}

func NewProcessor(s Storage) *Processor {
    return &Processor{storage: s}
}

func (p *Processor) Process(input string) (*Result, error) {
    // Returns concrete *Result, accepts Storage interface
    return &Result{Value: input}, nil
}

WRONG - Return interface unnecessarily

func NewProcessor(s *FileStorage) Storage {
    // Locks caller into interface, prevents direct method access
    return &Processor{storage: s}
}

Why This Works

Accepting interfaces:

  • Caller controls abstraction
  • Easy to mock/test
  • Flexible composition

Returning concrete types:

  • No hidden behaviors
  • All methods visible
  • Can add methods without breaking compatibility

When to Deviate

Return interface when:

func NewLogger(env string) io.Writer {
    // Valid: stdlib interface, multiple implementations
    if env == "prod" {
        return &fileLogger{}
    }
    return &consoleLogger{}
}

Return interfaces only when:

  • Using stdlib interfaces (io.Writer, io.Reader)
  • Multiple implementations chosen at runtime
  • Interface already well-established in ecosystem