agentleFS
h0rn3th0rn3t/golang-skills/skills/go-generics/SKILL.md

go-generics

Skill7 starsChanged 10 days agoApache-2.0View on GitHub

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.

The file

We split this skill into the rules it gives an agent

5 rules. About 0 are common, 3 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Start with concrete types.

    line 23
  2. Distinctive:

    Avoid generics when: only one type is ever instantiated.

    line 37
  3. Distinctive:

    Prefer standard-library constraints over hand-written ones:

    line 80
  4. Very specific:

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

    line 93
  5. Very specific:

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

    line 168

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
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:

NeedUse
<, > orderingcmp.Ordered (Go 1.21+) — not constraints.Ordered
Numeric unionWrite 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

  • go-interfaces: whether an interface already models the shared behavior.
  • go-style-core: declaration and scope mechanics for new types.
  • go-documentation: doc comments and examples for generic APIs.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.