CommunityWriting & Editinggithub.com

albertsko/go-skill

Use when writing, reviewing, debugging, or modernizing Go code in a module whose `go.mod` declares `go 1.27`.

What is go-skill?

go-skill is a Claude Code agent skill that use when writing, reviewing, debugging, or modernizing Go code in a module whose `go.mod` declares `go 1.27`.

Works with~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/albertsko/go-skill/tree/HEAD/skills/go-skill

Installed? Explore more Writing & Editing skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

Ask in your favorite AI

Open a new chat with this agent skill pre-loaded.

Documentation

1. Scope

These practices assume Go 1.27 language semantics, runtime defaults, and the default experiment configuration.

2. Route to concept files

Route by the code and task in scope, focusing on changed code for a change or diff. The index combines topics and illustrative code patterns. X, T, x, and v represent any name. Open every matching reference, including the additional routes below.

Find a practice by the ID prefix in its heading and cite its full ID. Follow Practice, use Example as the idiom, and consult Why, Exceptions, and Tradeoff for mechanisms, applicability, and costs. Signals identify potentially missing practices.

Also open these references for missing safeguards or symptoms:

  • Module or file language-version mismatches, build constraints, or runtime behavior overrides: MOD.
  • Code that checks or drops an error: ERH.
  • Goroutines or channels: CTX, GOR, and SHR.
  • Blocking I/O (network, database, HTTP, files) or an HTTP handler: CTX.
  • Tests of concurrent code: TBA and TST.
  • Memory or goroutine count that grows: PRO and MRT.
  • High GC CPU, or a program in a container: BRT, PRO, and TRC.
  • A hot path, or a request to make code faster: PRO, ALO, and BEN.

2.1 Language

  • CST code-structure.md: shadowing, package/built-in names (url, len, new, max), early returns (else after return), func init().
  • STD struct-design.md: getters/setters (GetX/SetX), embedding (sync.Mutex), promoted-field literals, functional options (NewXWithY, Config arguments), new(expr) and pointer helpers (ptr[T], intPtr).
  • INT interfaces.md: interface creation/ownership, single-implementation interfaces, concrete vs interface results, any/interface{}, typed nil interfaces/errors.
  • GEN generics.md: type parameters ([T any]), constraints (comparable, ~int, ~string, cmp.Ordered, golang.org/x/exp/constraints), inference, generic methods, self-referential constraints.
  • FNM functions-and-methods.md: value/pointer or mixed receivers, mutex-bearing value receivers, named results (n int, err error), naked returns.
  • LOP loops.md: range copies (v.field =), expression evaluation, per-iteration variables (v := v, &v, goroutine closures), range n, for i := 0; i <, slices.Backward, labeled breaks, break inside switch/select.
  • ITR iterators.md: iterator consumption/creation, iter.Seq/iter.Seq2 (including parameters), yield, iter.Pull, Next()/Value(), methods returning all elements as slices, slices.Collect.
  • DEF defer-and-cleanup.md: defer in loops, deferred argument/receiver evaluation, io.Closer cleanup (defer f.Close(), resp.Body, rows.Close()), Close/Sync errors, os.Create.

2.2 Data

  • NUM numbers.md: octal (0644), integer overflow (int32(, math.MaxInt), float ==, NaN/Inf, math.FMA.
  • SLC slices.md: length/capacity, append aliasing, preallocation (make([]), nil/empty ([]T{}, s == nil), len checks, copy/slices.Clone, [low:high:max], slice-to-array conversion.
  • COL collection-helpers.md: min/max, slices insert/delete/sort/search, maps, cmp, clear. Older forms: sort.Slice, math.Min/math.Max, append(s[:i], s[i+1:]...), map-clearing delete loops.
  • MAP maps.md: map sizing (make(map, map[K]V{}), sorted keys (maps.Keys, sort.Strings), writes during map iteration.
  • MRT memory-retention.md: caches/long-lived maps (map beside mutex, deletion, post-peak size), retained substrings/subslices, zeroing dropped pointers, strings.Clone/bytes.Clone, runtime.AddCleanup/runtime.SetFinalizer, unique.*, weak.*.
  • CMP comparison.md: comparable types (== on interfaces/structs, [T comparable]), slices.Equal/maps.Equal, reflect.DeepEqual, function values (runtime.FuncForPC).
  • STX strings-text.md: bytes/runes (len(s) as character count, []rune), UTF-8 validation (utf8), string(int), string range, unicode tables.
  • SPR strings-processing.md: Trim*/Cut*, SplitSeq/FieldsSeq/Lines, strings.Split/strings.Index, strings.Builder, string += loops, bytes/bytes.Buffer, fmt.Append*/strconv.Append*, []byte(fmt.Sprintf(.

2.3 Errors

  • PAN panics.md: panic vs error, recover, Must, panic(nil)/panicnil, debug.SetCrashOutput.
  • ERC errors-creating.md: wrapping (%w/%v, fmt.Errorf, context-free return err/return nil, err), errors.New, sentinels (var Err) vs error types (Error() string), errors.Join, ErrUnsupported.
  • ERH errors-handling.md: errors.Is/errors.AsType, err ==, err.(type), errors.As, message comparisons, timeout/cancellation sentinels (net.Error, os.ErrDeadlineExceeded, context.DeadlineExceeded), checking err before results, ignored errors (_ =, x, _ :=).
  • LOG logging.md: log/slog setup and error logging, log.Printf/log.Println, logging and returning the same error.

2.4 Concurrency

  • CND concurrency-design.md: concurrency vs parallelism, spawn thresholds (goroutine per element), worker pool sizing, runtime.NumCPU(), GOMAXPROCS.
  • SHR shared-state.md: data races, happens-before, race conditions, mutex vs channel, goroutine writes, sync.Mutex/RLock, formatting under locks (fmt.Sprintf), shared append/maps.
  • SYN sync-primitives.md: typed atomics (sync/atomic, atomic.Pointer, atomic.AddInt64/atomic.Value, goroutine n++), sync.Map, sync.Once/sync.OnceValue, sync.Cond, copied sync values.
  • GOR goroutine-lifecycle.md: goroutine leaks, stop plan/owner, senders blocked after early return, unbuffered result channels, go func(), sync.WaitGroup, wg.Add/wg.Go, errgroup (g.Go, SetLimit).
  • CHA channels.md: notification channels and sizing (make(chan, chan bool, chan struct{}), select priority, nil channels, close.
  • CTX context.md: passing context.Context, defer cancel()/context.WithTimeout, ctx.Done() around blocking operations, value keys (context.WithValue, ctx.Value), context.Background() outside main.
  • CXC context-cancellation.md: cancellation causes (ctx.Err(), <-ctx.Done(), context.Canceled/context.DeadlineExceeded/context.Cause, WithCancelCause), context.AfterFunc, background work (WithoutCancel, goroutine r.Context()), signal.Notify/signal.NotifyContext.

2.5 Standard library

  • TIM time.md: time.Duration units/bare numbers, time.Time comparison (==), timers in loops (time.After), time.NewTimer, time.Tick.
  • JSN json.md: encoding/json, encoding/json/v2, JSON tags (omitzero, omitempty), embedded marshalers, number decoding (json.Unmarshal into map[string]any).
  • SQL database-sql.md: database/sql, sql.Open, PingContext, pool size, query arguments/prepared statements (db.Query, .Exec, QueryRow, ExecContext, SQL via fmt.Sprintf), sql.Null[T], rows.Next/rows.Err.
  • IOF io-and-files.md: io.Reader/io.Writer and fs.FS parameters, filename string, os.Open, os.ReadFile, os.DirFS, os.Root, filepath.Join with user input.
  • HCL http-client-and-net.md: client timeouts/sharing/pools (http.Get, http.Post, http.DefaultClient, http.Client, http.Transport), net/netip vs net.IP/net.ParseIP, net.JoinHostPort vs fmt.Sprintf("%s:%d".
  • HSV http-server.md: handlers (http.ResponseWriter, *http.Request, http.Handler, r.Body/r.Method), ServeMux patterns/HandleFunc, http.Error, server timeouts (http.ListenAndServe, http.Server), MaxBytesHandler, ResponseController, CrossOriginProtection.
  • RND randomness-and-ids.md: uuid, crypto/rand, math/rand, math/rand/v2, rand.Seed.

2.6 Testing

  • TBA testing-basics.md: test categories/build tags (func TestX, //go:build integration), -race, t.Parallel, -shuffle, table-driven tests/t.Run, helpers, external _test packages.
  • TST testing-state.md: t.Cleanup, TestMain, t.Context vs test context.Background(), t.Chdir/t.Setenv/t.TempDir vs os.Chdir/os.Setenv/os.MkdirTemp, testing/synctest, test time/time.Sleep, cryptotest.
  • TTL testing-tools.md: httptest, testing/iotest, fstest, slogtest, fuzzing (func FuzzX).
  • BEN benchmarks.md: func BenchmarkX, b.Loop vs b.N/b.ResetTimer, representative input/reuse, benchstat.
  • COV coverage-and-test-output.md: -coverpkg, -cover, go build -cover/GOCOVERDIR, t.Output/t.Attr/t.ArtifactDir, test fmt.Println, go test -json.

2.7 Performance

Apply the layout, allocation, and inlining practices only to a hot path that a benchmark, profile, or trace has identified.

  • PRO profiling.md: pprof (net/http/pprof, /debug/pprof, runtime/pprof, pprof.Lookup), heap diffs, goroutine dumps, goroutineleak/block/mutex profiles (SetBlockProfileRate, SetMutexProfileFraction), labels (pprof.Do), goroutine counts (runtime/metrics).
  • TRC tracing.md: execution tracing (runtime/trace, trace.Start), flight recorder (FlightRecorder), latency spikes/rare slow requests, scheduling/GC pauses.
  • MLY memory-layout.md: cache locality/strides (hot []*T loops), false sharing (per-goroutine counters in one slice), instruction-level parallelism, field alignment, structs.HostLayout.
  • ALO allocations.md: escape analysis (-gcflags, returning local pointers), caller-owned buffers, compiler-elided conversions (hot string(b)), allocs/op, sync.Pool.
  • BRT build-and-runtime-tuning.md: inlining, PGO (default.pgo), GOGC/GOMEMLIMIT/debug.SetGCPercent, container-aware GOMAXPROCS (automaxprocs, runtime.GOMAXPROCS).
  • CGO cgo.md: batching cgo calls (import "C", C.), #cgo directives (noescape, nocallback).

2.8 Project and tooling

  • PKG packages-and-docs.md: project layout, package cohesion/names (util, common), aliases (type X = Y, //go:fix inline), doc comments, missing exported doc comments, Deprecated:, examples (func ExampleX).
  • TOL tooling.md: gofmt, go vet, linters (golangci-lint), tool directives/tools.go, go fix modernizers, test vet checks (-vet=), CI scripts, @latest.
  • MOD modules-and-builds.md: go.mod hygiene/replace, godebug///go:debug, workspaces (go.work), build constraints (//go:build, // +build).

3. Apply to the task

  • Writing code: satisfy every applicable practice in the routed files.
  • Reviewing code: when commands are available, first run go vet ./..., go test -race ./..., and go fix -diff ./..., using a copy if the code must remain untouched. Check every Signals bullet in every routed file. Exclude hits covered by Exceptions. Report the rest as ID | file:line | what is wrong | fix. For overlapping practices, cite the most specific ID first, then the others. Use - for problems no practice covers. Order by impact: wrong results, races, panics, leaks, hangs, then resource/performance problems, then outdated idioms/style.
  • Debugging: match symptoms to Signals and Why, confirm the mechanism in the code, then apply Practice.
  • Modernizing code: run go fix ./... until the diff is empty to apply the modernizers, then review the diff. Modernizers skip code shapes they cannot prove safe, so check the Signals of the routed files for the remaining outdated idioms and rewrite them by hand. Done when no Signals bullet of the routed files matches and go vet ./... and the tests pass.

Before claiming a performance gain, measure it with a benchmark or a profile.

Related Skills