| name | go-coding |
| description | Expertise in Go (Golang) development, including idiomatic patterns, concurrency, and performance optimization. Use when asked to write, refactor, or debug Go code. |
Go Coding Skill
This skill provides instructions for writing idiomatic, efficient, and robust Go code.
Core Principles
- Simplicity: Favor straightforward code over cleverness.
- Explicit over Implicit: Avoid magic; make logic clear.
- Error Handling: Treat errors as values. Always check returned errors.
- Concurrency: Use Goroutines and Channels for concurrent tasks. "Do not communicate by sharing memory; instead, share memory by communicating."
Implementation Guidelines
Project Structure
- Follow standard Go project layout (e.g.,
cmd/, internal/, pkg/).
- Use
go mod init <module-name> to initialize modules.
Formatting and Linting
- Always use
gofmt or goimports to format code.
- Use
go vet and golangci-lint for static analysis.
Performance
- Use
sync.Pool for frequently allocated objects.
- Profile using
pprof to identify bottlenecks.
- Be mindful of slice and map allocations; pre-allocate when size is known.
Testing
- Write unit tests using the
testing package (_test.go files).
- Use
testify or similar for easier assertions if allowed.
- Aim for high test coverage but prioritize critical logic.
Detailed Documentation
Common Patterns
Error Handling
if err := doSomething(); err != nil {
return fmt.Errorf("failed to do something: %w", err)
}
Goroutines and WaitGroups
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
process(id)
}(i)
}
wg.Wait()
Context for Cancellation
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
Useful Commands
- Build:
go build -o app ./cmd/app
- Test:
go test ./...
- Run:
go run ./cmd/app
- Tidy dependencies:
go mod tidy