| name | go |
| description | Expert Go programming skill authored by spf13 (former Go team lead, author of Cobra, Viper, Hugo, Afero). Covers idiomatic Go — package design, error handling, interfaces, concurrency, testing, and project layout. Use when writing, reviewing, or refactoring any Go code.
|
Idiomatic Go: The Go Way
Idiomatic Go patterns and best practices for building robust, efficient, and maintainable applications.
When to Activate
- Writing new Go code
- Reviewing or auditing existing Go code
- Refactoring Go code (especially code that looks like Java/Spring Boot patterns in Go)
- Designing Go packages, modules, or APIs
- Choosing between stdlib and third-party libraries
- Any question about Go project structure, error handling, concurrency, or testing
Core Principles
1. Clear is Better than Clever
Go favors readability and simplicity over abstraction and cleverness. Code should be obvious. If you have to read a function three times to understand its control flow, it needs to be rewritten.
func GetUser(id string) (*User, error) {
user, err := db.FindUser(id)
if err != nil {
return nil, fmt.Errorf("finding user %s: %w", id, err)
}
return user, nil
}
2. Make the Zero Value Useful
Design types so their zero value is immediately usable without initialization. This eliminates boilerplate constructors. sync.Mutex and bytes.Buffer are the gold standard for this.
type Counter struct {
mu sync.Mutex
count int
}
func (c *Counter) Inc() {
c.mu.Lock()
c.count++
c.mu.Unlock()
}
3. Return Early, Keep the Happy Path Left
Handle errors and edge cases immediately and return. Do not use else blocks for the main logic. The "happy path" of your function should never be indented.
Package Organization: Flat by Default
Anti-Pattern: Using deeply nested directory trees or relying heavily on an internal/ folder by default to artificially enforce "Clean Architecture" layers. This leads to circular dependencies and difficult navigation.
1. The Single-Package Default
Start flat. If you are building a microservice or a simple tool, put everything in the root directory (or alongside your main.go). Only create a new package when you truly need a new namespace to clarify the code, or when you need to decouple a strictly independent domain.
2. The Proper Use of internal/
The internal/ directory has a specific compiler enforcement: it prevents other modules from importing the code inside it.
- For Applications: If you are building an executable binary, nobody can import your code anyway. Using
internal/ here is usually just adding unnecessary path depth.
- For Libraries: Use
internal/ sparingly. It should be reserved for complex subsystems where you need to share exported types between your own packages, but absolutely must prevent end-users from relying on those types.
// Idiomatic: A flat, feature-focused library or simple app
myproject/
├── main.go # Entry point (if application)
├── server.go # Core logic
├── config.go # Configuration
├── parser.go # Domain specific parsing
├── parser_test.go
├── go.mod
└── go.sum
3. Domain Packages for Service Applications
When an application has genuinely distinct, independently-testable domains, give each its own top-level package. The rule is still one level deep — no internal/ nesting, no Clean Architecture layers. Each package owns one concern. main.go wires them together.
The signal to create a package: can this domain be described in one sentence, and does it have no knowledge of the other packages? If yes, it earns its own package.
// Idiomatic: A web service with distinct domain packages
myservice/
├── main.go # wires everything together; no business logic here
├── config/ # Config struct, env loading
├── auth/ # identity verification, session middleware
├── db/ # data store client + all queries
├── storage/ # blob storage (S3, R2, GCS)
├── billing/ # payment provider + credit ledger
├── jobs/ # job lifecycle + queue dispatch + worker handler (same domain, one package)
├── web/ # HTTP handlers + HTML templates + static assets (tightly coupled by design)
├── transcribe/ # domain-specific processing — independent pure functions
├── Makefile
├── Dockerfile
└── .env.example
Rules for domain packages:
- Each package has one clear purpose — name it after what it does, not what layer it is (
jobs/, not service/)
- Packages do not import each other sideways — cycles are a sign of wrong boundaries;
main is the wiring point
- Related sub-concerns that always travel together stay in one package (e.g. job creation + worker handler both live in
jobs/ because they share the job lifecycle domain)
- HTTP handlers and the templates they render belong together in
web/ — they are tightly coupled by design
- Do not create
utils/, helpers/, or common/ packages — these are symptoms of unclear ownership
Anti-pattern to reject: Clean Architecture / DDD layers (service/, repository/, controller/, domain/). These layer-named packages cause circular imports, force interface proliferation, and add zero clarity in Go. Domain-named packages (auth/, billing/, jobs/) are the correct middle ground between "too flat" and "over-engineered."
Interface Design
1. Interfaces are Discovered, Not Designed Upfront
Write concrete types first. Only define an interface when you discover that multiple types need to be used interchangeably by a consumer.
2. Define Interfaces Where They Are Used
Interfaces belong in the package that consumes them, not the package that implements them. This decouples your packages.
type UserFetcher interface {
GetUser(id string) (*User, error)
}
type Processor struct {
fetcher UserFetcher
}
3. Accept Interfaces, Return Structs
Require the smallest interface possible as an input parameter (e.g., io.Reader instead of *os.File), but return a concrete struct so callers aren't forced to use type assertions to access specific fields or methods.
Library API Design
Domain Object as Entry Point
When designing a Go library that wraps a stateful resource (a vault, a database connection, a config store), make that resource struct the primary object. Its methods return domain-typed sub-objects. Avoid:
- Passing a config/resource struct as the first argument to every package-level function
- Package-level global state (like pflag's default
FlagSet) for library code that may be embedded
Do this instead:
v, err := vault.Open(path)
idx, err := v.People()
note, err := v.Daily(time.Now())
mtgs, err := v.Meetings()
p, err := idx.FindOne("Steve")
Why this pattern:
- The primary struct (
Vault) is the single entry point — callers need just one import to get started
- Sub-packages define the rich domain types (
people.Person, daily.Note) — each type lives with the logic that owns it
- No global state means the library is safe for concurrent use, multiple instances, and testing
- Stateless method calls (reload fresh each time) keep the struct simple — no cache invalidation logic needed
- Type inference (
:=) means callers rarely need to explicitly import sub-packages for variable declarations
When to use a global instance instead: Only for CLI-only tools (like pflag itself) where there is truly only ever one instance and ease of use for end-users outweighs library correctness.
Concurrency Patterns
Anti-Pattern: Heavy, static Worker Pools.Go's scheduler is incredibly efficient; you don't need to manually manage pools of workers like OS threads in other languages.
1. Share Memory by Communicating
Don't use mutexes to protect shared data if you can pass that data over a channel instead. Channels orchestrate execution; mutexes serialize execution.
2. Bounded Concurrency (The Semaphore Pattern)
If you need to limit concurrency, use a buffered channel as a semaphore rather than a rigid worker pool.
func FetchAll(urls []string, maxConcurrent int) error {
sem := make(chan struct{}, maxConcurrent)
g, ctx := errgroup.WithContext(context.Background())
for _, url := range urls {
url := url
sem <- struct{}{}
g.Go(func() error {
defer func() { <-sem }()
return fetch(ctx, url)
})
}
return g.Wait()
}
3. Never Start a Goroutine Without Knowing How It Stops
Every go func() must have a clear exit condition, usually governed by a context.Context or a closed channel.
Configuration and Struct Design
Functional Options for Complex Initialization
When a struct has many optional configuration parameters, avoid massive constructors. Use the Functional Options pattern.
type Server struct {
addr string
timeout time.Duration
}
type Option func(*Server)
func WithTimeout(d time.Duration) Option {
return func(s *Server) { s.timeout = d }
}
func NewServer(addr string, opts ...Option) *Server {
s := &Server{
addr: addr,
timeout: 30 * time.Second,
}
for _, opt := range opts {
opt(s)
}
return s
}
Error Handling
1. Errors are Values
Errors aren't exceptions to be caught; they are values to be handled. Check them explicitly.
2. Wrap for Context, Not for Stack Traces
When returning an error, add context about what you were trying to do.
data, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("loading config file %s: %w", path, err)
}
Testing Patterns
Anti-Pattern: Relying on heavy BDD frameworks (like Ginkgo) or complex mocking generation tools. Go testing should just be Go programming.
1. Table-Driven Tests
The absolute standard for unit testing in Go. Iterate over a slice of structs containing inputs and expected outputs using t.Run().
func TestParseConfig(t *testing.T) {
tests := []struct {
name string
input string
wantErr bool
}{
{"valid config", "port=8080", false},
{"invalid format", "port=abc", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := ParseConfig(tt.input)
if (err != nil) != tt.wantErr {
t.Fatalf("ParseConfig() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
2. Meaningful Helpers with t.Helper()
When extracting repeated assertion logic, always call t.Helper() to ensure failures point to the actual test case, not the helper function line.
3. Fakes and Stubs over Heavy Mocks
Leverage Go's implicit interfaces to write simple, manual fakes. This keeps test dependencies lightweight and test logic transparent.
4. Golden Files and the testdata Directory
For tests requiring complex inputs or producing large outputs, use a directory named testdata. The go test tool explicitly ignores these directories.
5. Filesystem Abstraction (The Afero Pattern)
Do not hardcode os package calls deep within business logic. Accept an interface for the filesystem so tests can run in memory without touching the disk. github.com/spf13/afero is the industry standard for this.
import "github.com/spf13/afero"
type FileProcessor struct {
fs afero.Fs
}
func NewFileProcessor(fs afero.Fs) *FileProcessor {
return &FileProcessor{fs: fs}
}
In tests, inject afero.NewMemMapFs() to completely eliminate disk I/O and prevent flaky, slow tests.
6. cmp over DeepEqual
For comparing complex structs or maps, use github.com/google/go-cmp/cmp for rich, readable diffs instead of the strict reflect.DeepEqual.
Generics (Go 1.18+)
Generics exist to eliminate duplicated algorithms, not to create type hierarchies. If you are thinking about generics in terms of inheritance or polymorphism, stop — you are writing Java.
When to Use Generics
Use generics when you have the same algorithm that needs to operate on multiple concrete types:
func Map[S, T any](slice []S, f func(S) T) []T {
result := make([]T, len(slice))
for i, v := range slice {
result[i] = f(v)
}
return result
}
func Min[T cmp.Ordered](a, b T) T {
if a < b {
return a
}
return b
}
When NOT to Use Generics
type Repository[T any] interface {
Find(id string) (T, error)
Save(entity T) error
}
type UserStore interface {
FindUser(id string) (*User, error)
SaveUser(u *User) error
}
- Do not create generic base types, generic services, or generic repositories.
- Do not use
any as a constraint to mean "I don't know the type yet." That's a design smell.
- Do use
comparable when you need map keys or equality checks.
- Do use
cmp.Ordered when you need <, >, <=, >=.
- Start with a concrete implementation. Generify only when you have the same logic repeated across 3+ types.
Standard Library: Use the New Packages
LLMs frequently suggest third-party utilities or write manual helpers that have been in the standard library since Go 1.21. Always check stdlib first.
slices package (Go 1.21)
import "slices"
slices.Contains(s, "value")
slices.Index(s, "value")
slices.ContainsFunc(s, func(v string) bool { return v == "x" })
slices.Sort(s)
slices.SortFunc(s, func(a, b T) int { return cmp.Compare(a.Name, b.Name) })
slices.IsSorted(s)
slices.Reverse(s)
slices.Compact(s)
slices.Delete(s, i, j)
slices.Clone(s)
slices.Concat(s1, s2, s3)
Never write sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) when slices.Sort(s) exists.
maps package (Go 1.21)
import "maps"
maps.Keys(m)
maps.Values(m)
maps.Clone(m)
maps.Copy(dst, src)
maps.Delete(m, func(k, v T) bool { ... })
maps.Equal(m1, m2)
cmp package (Go 1.21)
import "cmp"
cmp.Compare(a, b)
cmp.Or(a, b, c)
min(a, b)
max(a, b)
cmp.Or is especially useful for default-value patterns:
cfg.Timeout = cmp.Or(cfg.Timeout, 30*time.Second)
errors.Join (Go 1.20)
err := errors.Join(err1, err2, err3)
if errors.Is(err, ErrNotFound) { ... }
Use this instead of fmt.Errorf("%w; %w", err1, err2) or any multierr package.
Concurrency: Modern Patterns
sync/atomic Typed Values (Go 1.19)
Use the typed atomic values instead of the function-based API:
var count int64
atomic.AddInt64(&count, 1)
val := atomic.LoadInt64(&count)
var count atomic.Int64
count.Add(1)
val := count.Load()
var flag atomic.Bool
var ptr atomic.Pointer[MyStruct]
var val32 atomic.Int32
var val64 atomic.Uint64
context.WithoutCancel (Go 1.21)
When you need to detach a context's cancellation but preserve its values (e.g., for a background task that should outlive a request):
bgCtx := context.WithoutCancel(requestCtx)
go doBackgroundWork(bgCtx)
HTTP: Use the Improved stdlib Router (Go 1.22)
LLMs reflexively recommend gorilla/mux or chi for any routing beyond the trivial. Since Go 1.22, the standard net/http ServeMux handles method and path-parameter routing natively.
mux := http.NewServeMux()
mux.HandleFunc("GET /users", listUsers)
mux.HandleFunc("POST /users", createUser)
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
})
mux.HandleFunc("GET /files/{path...}", serveFile)
Reach for chi or gorilla/mux only when you need middleware chaining, named route generation, or regex constraints. For pure method + path routing, the stdlib is sufficient.
Syntax: Use Current Go
LLMs frequently generate outdated syntax. Know the current idioms:
Range over Integer (Go 1.22)
for i := 0; i < 10; i++ { ... }
for i := range 10 { ... }
Build Constraints
The //go:build form is required since Go 1.17. Never emit the old // +build syntax.
any Instead of interface{}
func Print(v interface{}) { ... }
func Print(v any) { ... }
Structured Logging with log/slog (Go 1.21)
The skill note above covers basic setup. The patterns LLMs most often get wrong:
func HandleRequest(ctx context.Context, r *Request) {
logger := slog.With("request_id", r.ID, "user_id", r.UserID)
logger.Info("handling request")
process(ctx, logger, r)
}
logger.With(slog.Group("http",
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Int("status", status),
))
logger.Debug("cache miss", "key", key)
logger.Info("server started", "addr", addr)
logger.Warn("retrying", "attempt", n)
logger.Error("request failed", "err", err)
- Never use a package-level
log or slog global beyond main. Pass *slog.Logger as a dependency.
- Never log and return an error. Log at the boundary, return the error through the call stack.
- Use
slog.Default() as the fallback only in main or in libraries when no logger is provided.
Debugging: The Go Toolchain Is Not the Problem
The Go tool is extremely reliable. It is almost never the source of a bug.
When debugging, do not waste time suspecting go run, go build, go test, or the build cache. The Go toolchain does what it says:
go run always recompiles from source. It does not use a stale cached binary.
go build is deterministic and correct.
go test runs the actual compiled test binary.
- The build cache is keyed by source content — if the source changed, the cache is invalidated automatically.
If an error persists after you edit the code, the explanation is one of these — in order of likelihood:
- The edit did not fix the underlying logic error.
- The edit was made in the wrong file, wrong function, or wrong package.
- There is a second call site with the same bug that was not updated.
- The error is coming from a different code path than the one being edited.
What to do instead of blaming the tool:
- Re-read the error message carefully. Go's error messages are accurate.
- Confirm the file you edited is actually the file being compiled (
go list -f '{{.GoFiles}}' .).
- Add a
fmt.Println or t.Log at the exact site to verify execution reaches it.
- Check that all call sites of a changed function were updated.
Do not suggest clearing the build cache (go clean -cache), restarting the Go toolchain, or any other tool-level intervention before first exhausting all code-level explanations. The tool is not lying to you.