<go_language> <naming_conventions> Lowercase, single-word names. No underscores or mixedCaps. package httputil
<pattern name="exported">
<description>PascalCase for exported (public) identifiers.</description>
<example>
func ReadFile()
type Handler
var MaxRetries
</example>
</pattern>
<pattern name="unexported">
<description>camelCase for unexported (private) identifiers.</description>
<example>
func parseConfig()
type handler
var maxRetries
</example>
</pattern>
<pattern name="interfaces">
<description>Single-method interfaces: method name + "er" suffix.</description>
<example>
Reader, Writer, Closer, Stringer, Handler
</example>
</pattern>
<pattern name="acronyms">
<description>Keep acronyms uppercase: URL, HTTP, ID, API.</description>
<example>
func ServeHTTP()
type HTTPClient
var userID
</example>
</pattern>
<pattern name="getters">
<description>No "Get" prefix for getters.</description>
<example>
func (u *User) Name() string // not GetName()
</example>
</pattern>
</naming_conventions>
<type_system> Zero values are meaningful: 0, "", nil, false. var buf bytes.Buffer // ready to use, no initialization needed
<pattern name="type_assertion">
<description>Safe type assertion with ok pattern vs unsafe panic.</description>
<example>
value, ok := x.(Type) // safe
value := x.(Type) // panics if wrong type
</example>
</pattern>
<pattern name="type_switch">
<description>Type switch for handling multiple types.</description>
<example>
switch v := x.(type) {
case string: // v is string
case int: // v is int
default: // v is any
}
</example>
</pattern>
</type_system> </go_language>
<error_handling> Errors are values, not exceptions Handle errors explicitly at each call site Return errors, don't panic Add context when propagating errors
func (e \*ValidationError) Error() string {
return fmt.Sprintf("validation failed for %s: %s", e.Field, e.Message)
}
</example>
// Extract custom error type
var valErr \*ValidationError
if errors.As(err, &valErr) {
log.Printf("field: %s", valErr.Field)
}
</example>
<modern_go_features> Green Tea garbage collector is now enabled by default in Go 1.26, improving GC performance. The built-in new function now allows an expression specifying the initial value (Go 1.26). p := new(MyStruct{Field: "value"}) Generic types may now refer to themselves in their own type parameter list (Go 1.26). Range over integers for simple iteration (Go 1.22+). for i := range 10 { fmt.Println(i) } Range over iterator functions (Go 1.23+). for v := range slices.Values(s) { fmt.Println(v) } Baseline cgo overhead reduced by approximately 30% in Go 1.26. </modern_go_features>
<common_interfaces> Read(p []byte) (n int, err error) Write(p []byte) (n int, err error) Close() error Error() string String() string </common_interfaces>
go 1.26
toolchain go1.26.0
require (
github.com/pkg/errors v0.9.1
golang.org/x/sync v0.3.0
)
require (
golang.org/x/sys v0.10.0 // indirect
)
</example>
<project_structure> <standard_layout> Main applications (cmd/myapp/main.go) Private packages, not importable externally Public library code (optional, controversial) API definitions (OpenAPI, protobuf) Configuration files Build/install scripts Test fixtures </standard_layout>
<best_practices> cmd/myapp/main.go should be minimal - call into internal packages internal/ packages cannot be imported from outside parent module Each directory = one package (except _test packages) </best_practices> </project_structure>
<pattern name="with_waitgroup">
<description>Use sync.WaitGroup to wait for multiple goroutines to complete.</description>
<example>
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
go func(item Item) {
defer wg.Done()
process(item)
}(item)
}
wg.Wait()
</example>
</pattern>
<pattern name="buffered">
<description>Buffered channels allow asynchronous communication up to buffer size.</description>
<example>
ch := make(chan int, 10)
</example>
</pattern>
<pattern name="receive_only">
<description>Receive-only channel parameter.</description>
<example>
func consumer(ch <-chan int)
</example>
</pattern>
<pattern name="send_only">
<description>Send-only channel parameter.</description>
<example>
func producer(ch chan<- int)
</example>
</pattern>
<pattern name="select">
<description>Select statement for multiplexing channel operations.</description>
<example>
select {
case msg := <-ch1:
handle(msg)
case ch2 <- value:
// sent
case <-ctx.Done():
return ctx.Err()
default:
// non-blocking
}
</example>
</pattern>
<pattern name="close_channel">
<description>Closing channels signals no more values will be sent.</description>
<example>
close(ch)
for v := range ch { } // receive until closed
</example>
</pattern>
select {
case result := <-doWork(ctx):
return result, nil
case <-ctx.Done():
return nil, ctx.Err()
}
</example>
<sync_package> Mutual exclusion lock Read-write lock Execute exactly once Wait for goroutine completion Concurrent map (specialized use cases) </sync_package>
<standard_library_additions> Structured logging with log/slog (Go 1.21+). Recommended over log and third-party loggers for new projects. import "log/slog"
slog.Info("user logged in",
"user_id", userID,
"ip", request.RemoteAddr,
)
// With structured logger
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("request", "method", r.Method, "path", r.URL.Path)
</example>
slices.Sort(names)
if slices.Contains(names, "alice") { ... }
idx := slices.Index(names, "bob")
keys := slices.Collect(maps.Keys(m))
</example>
// Default value pattern
name := cmp.Or(userInput, envVar, "default")
// Ordered comparison
result := cmp.Compare(a, b)
</example>
func getUser(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
// ...
}
</example>
<build_commands> Compile package <use_case>Build executable from current package</use_case> Specify output name Output binary name <use_case>Build with custom binary name</use_case> Compile and install to GOPATH/bin <use_case>Install package for global use</use_case> Compile and run Go file to execute <use_case>Quick compile and execute for development</use_case> Format all code All packages recursively <use_case>Standardize code formatting</use_case> Static analysis All packages recursively <use_case>Detect suspicious code constructs</use_case> Run code generators <use_case>Execute //go:generate directives</use_case> Standard meta-linter aggregating multiple linters <use_case>Run comprehensive linting with golangci-lint run</use_case> Cross-compile for different platforms GOOS=linux GOARCH=amd64 go build <use_case>Build binaries for different operating systems and architectures</use_case> </build_commands>
<context7_integration> Use Context7 MCP for up-to-date Go documentation
<go_libraries> </go_libraries>
<usage_patterns> Retrieve Go module documentation from Context7. get-library-docs context7CompatibleLibraryID="/golang/website" topic="go.mod modules" </usage_patterns> </context7_integration>
<best_practices> Use gofmt/goimports for consistent code formatting Handle errors explicitly at each call site Accept interfaces, return concrete types Keep interfaces small (1-3 methods) Use context.Context for cancellation and timeouts Prefer table-driven tests for comprehensive coverage Use t.Helper() in test helper functions Run tests with -race flag to detect data races Define interfaces where they are used, not implemented Use go mod tidy regularly to maintain clean dependencies </best_practices>
<anti_patterns> Overusing init() functions makes code harder to test and reason about. Prefer explicit initialization functions that can be called with parameters. Package-level mutable variables create hidden dependencies and concurrency issues. Pass dependencies explicitly through function parameters or struct fields. Defining interfaces prematurely adds unnecessary abstraction. Define interfaces when you have multiple implementations or need to decouple packages. Naked returns in long functions reduce code clarity. Use explicit return statements for functions longer than a few lines. Using panic for recoverable errors violates Go's error handling philosophy. Return errors as values and handle them explicitly at each call site. Goroutines that never exit waste resources and can cause memory leaks. Use context.Context or done channels to ensure goroutines can be cancelled. Data races lead to unpredictable behavior and bugs. Use sync primitives (Mutex, RWMutex) or channels, and always run tests with -race flag. Overusing interface{}/any loses type safety and requires type assertions. Use concrete types or small, focused interfaces when possible. </anti_patterns>
<error_escalation inherits="core-patterns#error_escalation"> golangci-lint style warning Compilation error Breaking change in exported API Data race or unsafe memory operation </error_escalation>
<related_skills> Navigate Go packages and symbol definitions efficiently Access latest Go standard library and toolchain documentation Debug goroutine leaks, race conditions, and performance issues </related_skills> <related_agents> Locate code patterns and references in this skill domain Review implementation quality against this skill guidance Analyze code complexity and suggest refactoring improvements </related_agents>