go-generics
/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.
- Author
- h0rn3t ↗
- Repository
- golang-skills ↗
- Licence
- Apache-2.0
- Last repository change
- 27.10.2026
Assessment and security
- Files in this package
- 2
- Scripts
- 0
- HTML comments
- 0
- URLs in SKILL.md
- 0
No signals detected. Repository changed on 27.10.2026, without references to retired models or APIs.
Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.
What it does and when to use it
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.
Original author 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.
How it works
- Resource Routing
- When to Use Generics
- Generic Methods (Go 1.27+)
- Constraints
- Type Aliases vs Type Definitions
- Common Pitfalls
- Related Skills
SKILL.md preview
---
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.
---
# Go Generics and Type Parameters
> Compatibility: Baseline Go 1.27 (see the plugin repository's 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.
```go
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](../go-interfaces/SKILL.md#generic-methods-cannot-satisfy-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` |
```go
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:
```go
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.
```go
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:
```go
// 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:
```go
// 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](../go-interfaces/SKILL.md): whether an interface already models the shared behavior.
- [go-style-core](../go-style-core/SKILL.md): declaration and scope mechanics for new types.
- [go-documentation](../go-documentation/SKILL.md): doc comments and examples for generic APIs.
Files in this package (2)
- SKILL.md 7 KB
- references/CONSTRAINTS.md 1 KB
Versions
| Repository | Score | Licence |
|---|---|---|
| This page · h0rn3t/golang-skills | 100 | Apache-2.0 |
| muratmirgun/gophers | 100 | MIT |
| muratmirgun/gophers | 100 | MIT |
| cxuu/golang-skills | 100 | Apache-2.0 |
Database snapshot: 13.11.2026 · package version 7dd6fc7ac0bd (SHA-256 digest of the entire package)
Downloads in the last 30 days: 0 · ranking
Similar skills
- 100go-interfaces
Use when designing or implementing Go interfaces, abstractions, mockable boundaries, embedding, assertions, type switches, pointer versus value receiver types, or interface versus concrete API types. Generics belong to go-generics. - 100go-generics-and-interfaces
Use this skill when authoring type-parameterized collections, functional utilities, and decoupled interfaces in Go 1.18+. - 95java-generics
Use when Java generics including type parameters, wildcards, and type bounds. Use when writing type-safe reusable code. - 95python-type-system
Use when Python's type system including type hints, mypy, Protocol, TypedDict, and Generics. Use when working with Python type annotations. - 100python-type-safety
Python type safety with type hints, generics, protocols, and strict type checking. Use when adding type annotations, implementing generic classes, defining structural interfaces, or configuring mypy/pyright. - 100developing-with-typescript
TypeScript 5.x development with type system, generics, utility types, and strict mode patterns. Use when writing TypeScript code or adding types to JavaScript projects.