AGENT SKILL

go-generics

Use when choosing or writing Go generics, constraints, type aliases versus definitions, or utilities for multiple types. Non-generic interface design belongs to go-interfaces.

License 许可
Apache-2.0
最近更新
2026-11-14
Stars
★ 7
Forks
2

01 前言 Front Matter

name
go-generics
description
Use when choosing or writing Go generics, constraints, type aliases versus definitions, or utilities for multiple types. Non-generic interface design belongs to go-interfaces.

02 资源文件 1

03 SKILL.md 正文

Go Generics and Type Parameters

Compatibility: Baseline Go 1.27 (see COMPATIBILITY.md). Generic methods require Go 1.27+, and the compiler gates them by the go directive: at go 1.26 it rejects one with generic method requires go1.27 or later. Inference in function-type conversions and composite-literal elements (Go 1.27+) and self-referential constraints (Go 1.26+) are not gated — they compile on a 1.27 toolchain at an older directive and fail on the older toolchain itself, so verify them on the CI toolchain. Generic type aliases Go 1.24+; generics themselves, Go 1.18+.

Resource Routing

  • references/CONSTRAINTS.md - Read when composing constraints or supplying type arguments explicitly.

When to Use Generics

Start with concrete types. Generalize only when a second type appears.

Do multiple types share identical logic?
├─ No  → concrete types
└─ Yes → Do they share a useful interface?
         ├─ Yes → interface
         └─ No  → generics

Prefer generics when: multiple types share identical logic (sort, filter, map/reduce); the alternative is any plus type switching; you are building a reusable container.

Avoid generics when: only one type is ever instantiated; an interface already models the shared behavior; the generic version is harder to read.


Generic Methods (Go 1.27+)

Methods may declare their own type parameters, independent of the receiver's. This removes the old workaround of a package-level generic function taking the receiver as its first argument.

type Store struct{ data map[string]any }

// Go 1.27: the type parameter belongs to the method
func (s *Store) Get[T any](key string) (T, bool) {
    v, ok := s.data[key].(T)
    return v, ok
}

n, ok := store.Get[int]("count")

Constraints:

  • A generic method cannot satisfy an interface; go-interfaces owns that rule and the assertion that catches it.
  • The receiver's own type parameters stay on the receiver; do not redeclare them.
  • Reflection does not see a generic method (MethodByName, NumMethod): a method that text/template, html/template, or RPC calls by name stays non-generic, or the template fails at run time.
  • Same restraint as generic functions: add the parameter when a second type actually appears, not in anticipation.

Go 1.27 extends function type inference to all assignments and conversions to matching function types, composite-literal elements included (S{f: id}, []func(int) int{id}). Assignment to a typed variable already supported inference in Go 1.21. Prefer inference when the call site remains clear.


Constraints

Prefer standard-library constraints over hand-written ones:

Need Use
<, > ordering cmp.Ordered (Go 1.21+) — not constraints.Ordered
Numeric union Write a local union; the constraints module is still x/exp
type Numeric interface {
    ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~float32 | ~float64
}

Use ~ for underlying types so named types (type Celsius float64) satisfy the constraint, and | for unions.

Self-referential constraints (Go 1.26+)

A type parameter may appear in its own constraint, so a constraint can require that a type combines with, compares to, or produces its own kind:

type Adder[A Adder[A]] interface{ Add(A) A }

func Sum[A Adder[A]](zero A, xs ...A) A {
    for _, x := range xs {
        zero = zero.Add(x)
    }
    return zero
}

Reach for it only when the method genuinely takes or returns the implementing type; comparable or cmp.Ordered covers equality and ordering. Go 1.25 rejects the declaration as an invalid recursive type, and the go directive does not gate it (see the Compatibility note).

Hashing generic keys

hash/maphash.Hasher[K] (Go 1.27+) is the seam between a hash-based container and its keys: one hash function plus the matching equivalence relation. It buys what the built-in map cannot do — keys that are not comparable, or an equality other than == — so constrain the container to any, not comparable. maphash.ComparableHasher[K]{} is the ready-made implementation for ordinary keys; a custom Hasher is a two-method type.

type table[K, V any] struct {
    hasher maphash.Hasher[K] // maphash.ComparableHasher[string]{} at an ordinary call site
    seed   maphash.Seed      // maphash.MakeSeed() per table; a zero Seed panics in SetSeed
}

func (t *table[K, V]) hash(k K) uint64 {
    var h maphash.Hash
    h.SetSeed(t.seed)
    t.hasher.Hash(&h, k)
    return h.Sum64()
}

A Hasher must be logically stateless, and Equal(x, y) must imply an equal hash — the container relies on both. ComparableHasher is itself constrained to comparable, so it can only be named where the key type is concrete: inside a K any container the field stays the Hasher[K] interface.


Type Aliases vs Type Definitions

Type aliases (type Old = new.Name) are rare — use for package migration or gradual API refactoring. Generic type aliases (Go 1.24+) are legal (type Set[T comparable] = map[T]struct{}) and carry the same caution: an alias adds a name, not a type, so it buys nothing but a migration path.


Common Pitfalls

Don't wrap standard library types. A single-use generic is indirection:

// Bad
type Set[T comparable] struct{ m map[T]struct{} }

// Better
seen := map[string]struct{}{}

Don't use generics for interface satisfaction. If T is only used to satisfy an interface, accept the interface — unless T is a slice element:

// Bad
func Process[T io.Reader](r T) error

// Good
func Process(r io.Reader) error

// Good: a []*os.File is not a []io.Reader, so the slice keeps T
func ProcessAll[T io.Reader](rs []T) error

Don't over-constrain. comparable beats interface{ ~int | ~string } when you only need ==, but it admits interface types: == or a map key on T panics at run time when a caller passes any holding a slice or map.


Related Skills

04 同仓库更多 Skills

h0rn3t
h0rn3t/golang-skills

go-troubleshooting

Use when investigating a bug or ticket in a Go service whose cause is unknown — wrong or missing results, tenant-specific behavior, a regression, stage/prod/CI differences, a panic, hang, deadlock, leak, unexplained CPU/RSS growth, or a flaky test. Also use for pasted stack traces, profiles, logs, or requests to find a Go issue's root cause, even without the word debug. Does not cover rewriting ticket text, implementing an already-diagnosed fix alone (use its topic skill), or optimizing a known bottleneck (see go-performance).

★ 7
h0rn3t
h0rn3t/golang-skills

go-testing

Use when writing, reviewing, or improving Go test code — including table-driven tests, subtests, parallel tests, test helpers, test doubles, and assertions with cmp.Diff. Also use when a user asks to write a test for a Go function, even if they don't mention specific patterns like table-driven tests or subtests. Does not cover benchmark performance testing (see go-performance).

★ 7
h0rn3t
h0rn3t/golang-skills

go-style-core

Use when resolving Go style or language mechanics such as formatting, nesting, declarations, initialization, scope, shadowing, loops, switches, or enum zero values. API design, naming, errors, and tests have specialized skills.

★ 7
h0rn3t
h0rn3t/golang-skills

go-security

Use when writing or reviewing Go code that touches untrusted input, secrets, or credentials — SQL, shell, or template injection, path traversal, SSRF, cookies and security headers, password hashing, TLS settings, token comparison, or what may appear in a log line. Also use when a handler accepts a file name, URL, or command argument from a client, or when asked to find "vulnerabilities", even if the user never says "security". Does not cover the os.Root and crypto/rand mechanics (see go-defensive) or the dependency CVE scan in the gate (see go-linting).

★ 7
h0rn3t
h0rn3t/golang-skills

go-resilience

Use when handling Go dependency failures or overload with retries, backoff/jitter, budgets, idempotency, duplicate delivery, circuit breakers, bulkheads, rate limits, backpressure, or degradation. Unknown root causes belong to go-troubleshooting.

★ 7
h0rn3t
h0rn3t/golang-skills

go-performance

Use when optimizing slow or performance-critical Go code, allocations, string concatenation in loops, or benchmarks. Also use when writing or reviewing a cache, including implementing one from a stub — its key, its expiry, and how a miss loads. Concurrent code patterns belong to go-concurrency.

★ 7