How do I expose only minimal public APIs in Go projects?

In Go projects, exposing only minimal public APIs is essential for maintaining clean code and ensuring that your software remains easy to maintain and evolve. By following certain practices, you can keep your public API surface small and focused on the features that should be accessible to users of your package.

Best Practices for Minimal Public APIs

  • Use unexported types and functions internally when possible.
  • Only export types, functions, or variables that need to be accessed from outside the package.
  • Group related functionalities into cohesive packages to limit access to only what's necessary.
  • Provide a clear and thorough documentation for public APIs to guide users.
  • Review and refactor your public API regularly to remove any deprecated or unused features.

Example of Minimal Public API in Go

// Package shapes provides a simple API for shape calculations. package shapes // Circle represents a circle shape. type Circle struct { radius float64 // unexported attribute } // NewCircle creates a new Circle instance. func NewCircle(r float64) *Circle { return &Circle{radius: r} } // Area calculates the area of the circle. func (c *Circle) Area() float64 { return 3.14 * c.radius * c.radius // public method }

Go Public API Minimal API Clean Code Go Packages