Twelve Patterns for Writing Idiomatic Go With Claude Code
Twelve Claude Code patterns for idiomatic Go: interface-first prompts, test-driven loops, CLAUDE.md rules, error wrapping, concurrency and Plan Mode limits.
This article is published in English.
Sources: Master Claude Code in Golang: 12 Patterns for Agentic Developers
Software gets built differently now. Fewer people type every line themselves, and more of them direct a tool. With Claude Code, Anthropic's terminal agent, a new role has appeared: the agentic engineer. The payoff doesn't come from lazy prompts. It comes from working inside real systems, relying on project memory and steering the model from the terminal.
The blunt truth is that opening a shell and typing claude "build a Golang REST API" produces a messy codebase. Pairing with Claude Code on production Go 1.26 projects is rough at first. Over time a set of habits emerges that yields solid, normal-looking Go. These are twelve of them.
1. Interface-first prompts
Idea: Instead of asking for a huge system in one go, define the Go interface first. That locks down the rules, and the model then writes code to match them.
Best for: Services that talk to databases, external APIs or odd domain logic. It also stops Claude from inventing methods that don't exist.
# Terminal Command:
claude "Implement the PaymentGateway interface using Stripe in stripe.go. Ensure all methods return mapped domain errors, not raw stripe errors."
// Go Interface Contract:
type PaymentGateway interface {
Charge(ctx context.Context, amount int64) (string, error)
Refund(ctx context.Context, transactionID string) error
}
2. Test-driven generation
Approach: Test-driven development gets a boost. Write the tests by hand, or have the AI draft them. Because Claude Code can execute shell commands, it can run the suite and keep fixing the implementation until everything passes.
Useful for: Tricky math, parsers and anything with irritating edge cases.
# Terminal Command:
claude "Run `go test -v ./calc` and implement calculator.go to make these exact tests pass without changing the test assertions."
// Go Test File:
func TestCalculateDiscount(t *testing.T) {
result := CalculateDiscount(100, "VIP")
if result != 80 {
t.Errorf("Expected 80, got %d", result)
}
}
3. Enforcing context rules with CLAUDE.md
Concept: Models sometimes forget Go's conventions around context. Project memory fixes that for good. Put the team's rules into a CLAUDE.md file and Claude Code follows them every session.
Good fit: Network calls, database access and anything slow enough that it may need cancelling.
# Excerpt from CLAUDE.md:
## Go Conventions
Rule: Every exported I/O or database method MUST accept `context.Context` as its first parameter and pass it to the underlying driver (e.g., using `QueryRowContext`).
4. Explicit error wrapping
Principle: Descriptive errors aren't exactly loved by Go developers, but they're necessary. Left alone, Claude tends to return a bare err. It has to be told to use fmt.Errorf with the %w verb so the error chain survives.
Typical use: Any call into the standard library or a third-party package that can fail.
# Terminal Command:
claude "Refactor config.go. If os.Open fails, wrap the error with context using fmt.Errorf and the %w verb."
// Generated Go Code:
file, err := os.Open("config.json")
if err != nil {
return fmt.Errorf("failed to open config file: %w", err)
}
5. Concurrency scaffolding
Core move: Concurrency in Go is great and easy to get wrong. Rather than asking for something faster, name the primitives wanted, such as a sync.WaitGroup or buffered channels. Don't leave the AI to guess.
Handy when: Batch jobs, worker pools and fan-out/fan-in pipelines.
# Terminal Command:
claude "Implement a worker pool for the Job slice in worker.go. Use a buffered channel of size 5 and a sync.WaitGroup. Ensure the WaitGroup is closed cleanly."
// Go Code Scaffold:
jobs := make(chan Job, 5)
var wg sync.WaitGroup
// Claude generates the exact worker loop here based on the constraints
6. Type-driven development
Technique: Stop using strings for everything. Skilled agentic engineers ask Claude for custom types for IDs and statuses, so Go's strict compiler does the policing.
Ideal for: Structs cluttered with plain strings or ints.
# Terminal Command:
claude "Refactor the User struct. Change all string IDs to a custom type UserID string, and ensure all functions accepting an ID use this new type."
// Generated Go Code:
type UserID string
type User struct {
ID UserID
Email string
}
7. Dependency injection directives
Gist: Left to itself, an AI will wire a struct straight to the database inside its constructor. Force dependency injection by instructing it to take collaborators as arguments.
Most helpful in: Handlers, services and repositories that need to be unit tested later.
# Terminal Command:
claude "Rewrite NewOrderService. Do not initialize the logger inside. Pass a *zap.Logger and a PaymentGateway interface as dependencies."
// Generated Go Code:
func NewOrderService(logger *zap.Logger, gateway PaymentGateway) *OrderService {
return &OrderService{
logger: logger,
gateway: gateway,
}
}
8. Benchmark-led tuning
The trick: Guessing which code is slow wastes time. Run Go's standard benchmarks and pipe the output into the Claude Code CLI, then ask for a fix for the memory issues. Even with the Green Tea garbage collector in Go 1.26, allocations still deserve attention.
Works well for: Hot paths where the collector is under pressure.
# Terminal command piping benchmark results directly to Claude Code:
go test -bench . -benchmem | claude "Our allocs/op is too high in the parser. Rewrite the parse function to use a sync.Pool for the byte slices."
// Generated Go Code:
var bufferPool = sync.Pool{
New: func() any {
b := make([]byte, 1024)
return &b
},
}
9. Struct tags from raw payloads
Method: Writing JSON or XML tags by hand is tedious. Hand Claude the raw JSON and have it produce the exact Go struct with every tag in place.
Suits: Consuming third-party webhooks, or building APIs with frameworks like Gin or Fiber.
# Terminal Command:
claude "Create a Go struct from this JSON payload. Add `json` tags, and include `validate` tags ensuring the email is valid and the age is >= 18."
// Generated Go Code:
type RegistrationRequest struct {
Email string `json:"email" validate:"required,email"`
Age int `json:"age" validate:"gte=18"`
}
10. Idiomatic GoDoc
How it works: Documentation is a chore, but good code needs it. Ask Claude Code to read a file and produce natural GoDoc comments for every exported identifier. It can even be wired up to run automatically.
Shines with: Preparing a package for open source, or keeping a team's code tidy.
# Terminal Command:
claude "Add GoDoc comments to all exported types and functions in user_repo.go. Start the comment with the name of the identifier."
// Generated Go Code:
// UserRepository handles database operations for the User entity.
type UserRepository struct {
db *sql.DB
}
11. The compile-error loop
Pattern: When a build breaks, fixing the typo by hand is often unnecessary. Claude Code can run the build, read the red output and repair the problem, looping until it compiles.
Reach for it on: Import cycles, or fifty type errors left behind by a big refactor.
# Terminal Command:
claude "Run `go build ./...`. If it fails with type conversion errors, fix the casts in handler.go and retry until it compiles cleanly."
// Claude correctly casts the primitive to the custom type to fix the build:
userID := UserID(user.ID)
err := repo.GetByID(ctx, userID)
12. Architectural boundaries with Plan Mode
Rule of thumb: Models love to blur layers, for instance by dropping raw SQL into an HTTP handler. Boundaries have to be set explicitly. Claude Code's Plan Mode lets you review the proposed approach before it writes 500 lines of unusable code.
Natural home: Keeping an application clean and consistent with Domain-Driven Design rules.
# Terminal Command:
claude "Create a new Order handler. Rule: Do not import the 'database/sql' package in this file. You may only interact with the database via the OrderUseCase interface. Use plan mode to show me the approach first."
// Generated Go Code:
func (h *OrderHandler) Create(w http.ResponseWriter, r *http.Request) {
// Claude generates clean HTTP handling without leaking DB logic here
}
Guiding instead of fighting
The image of the lone programmer typing away in a dark basement is fading. People who can explain what they want clearly, set firm rules and let the AI handle the heavy lifting get to spend their time on the interesting architectural questions. Applying these twelve patterns means no longer fighting the tool. Claude Code gets steered toward Go that is safe, fast and unremarkable in the best sense.
Nobody writes perfect code on the first try, and Claude doesn't either. With the right rules in place, it gets very close.