AgentSkillsCN

go-coding-standards

当你需要编写、审查或重构Go代码时,这一技能将为你提供错误处理模式、项目布局、并发编程与接口设计的指导。

SKILL.md
--- frontmatter
name: go-coding-standards
description: Use when writing, reviewing, or refactoring Go code. Provides error handling patterns, project layout, concurrency, and interface design guidelines.
allowed-tools: Read, Grep, Glob

Go Coding Standards

This skill provides modern Go coding guidelines and best practices for this project.

When to Apply

Apply these standards when:

  • Writing new Go code
  • Reviewing or refactoring existing Go code
  • Designing package APIs and interfaces
  • Implementing error handling strategies

Core Principles

  1. Simplicity Over Cleverness - Clear, readable code beats clever abstractions
  2. Composition Over Inheritance - Use interfaces and embedding
  3. Explicit Over Implicit - Make behavior obvious, avoid magic
  4. Fail Fast - Return errors early, handle them explicitly

Quick Reference

Must-Use Patterns

PatternUse Case
Error wrappingfmt.Errorf("context: %w", err) for error chains
Table-driven testsMultiple test cases in structured format
Functional optionsConfigurable constructors with defaults
Interface segregationSmall, focused interfaces (1-3 methods)
Context propagationPass context.Context as first parameter

Must-Avoid Anti-Patterns

Anti-PatternAlternative
Ignoring errorsAlways handle: if err != nil { return err }
Panic for expected failuresReturn error type
Package-level stateDependency injection
Large interfacesSmall, composable interfaces
Deep package nestingFlat, focused packages
init() functionsExplicit initialization

Detailed Guidelines

For comprehensive guidance, see:

Code Style

Naming Conventions

ItemConventionExample
Packagesshort, lowercase, singularuser, http, json
ExportedPascalCaseNewServer, UserService
UnexportedcamelCaseparseConfig, handleRequest
Interfaces-er suffix for single methodReader, Writer, Closer
Acronymsconsistent caseHTTPServer, xmlParser

Documentation

go
// Package user provides user management functionality.
package user

// User represents a registered user in the system.
// It contains the user's identity and profile information.
type User struct {
    ID    string
    Email string
    Name  string
}

// NewUser creates a new User with the given email.
// Returns an error if the email format is invalid.
func NewUser(email string) (*User, error) {
    // ...
}

Tooling

Always run these before committing:

bash
go fmt ./...           # Format code
go vet ./...           # Static analysis
go test ./...          # Run tests
go mod tidy            # Sync dependencies

Consider adding:

  • golangci-lint - Comprehensive linter
  • staticcheck - Advanced static analysis

References