Write Generic Functions in Go With comparable, cmp, slices, and maps
Use type parameters with comparable and cmp.Ordered alongside Go's standard slices and maps packages. After this, you eliminate duplicate helpers without losing type safety.
Before Go 1.18, writing reusable collection helpers forced an awkward trade-off: either duplicate DedupeStrings, DedupeInts, and DedupeIDs across your codebase, or accept []any and lose compile-time type checking while paying runtime boxing allocations.
Go generics give you type-safe parameterized functions that preserve the caller's exact return type—while Go's standard cmp, slices, and maps packages already cover most sorting, deduplication, and map-key operations without writing custom loops at all.
Skip ahead
Jump straight to Dedupe and MaxOf or the constraints comparison table.
Why constraints matter (and how Go compiles generics)
Unlike C++ templates that blindly duck-type at instantiation, Go requires you to state upfront in [T Constraint] what operations your function needs on T. That way, the compiler checks your generic function once even before anyone calls it, and callers get clear compile errors if they pass an incompatible type (such as trying to compare two structs containing slices with ==).
Working with comparable, cmp.Ordered, slices, and maps
package main
import (
"cmp"
"fmt"
"maps"
"slices"
)
func Dedupe[T comparable](in []T) []T {
seen := make(map[T]struct{}, len(in))
out := make([]T, 0, len(in))
for _, v := range in {
if _, ok := seen[v]; !ok {
seen[v] = struct{}{}
out = append(out, v)
}
}
return out
}
func MaxOf[T cmp.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
func main() {
nums := Dedupe([]int{3, 1, 3, 2, 1})
slices.Sort(nums)
fmt.Println("deduped sorted:", nums)
fmt.Println("max string:", MaxOf("go", "rust"))
m := map[string]int{"b": 2, "a": 1}
keys := slices.Sorted(maps.Keys(m))
fmt.Println("sorted keys:", keys)
}
$ go run .
deduped sorted: [1 2 3]
max string: rust
sorted keys: [a b]
Choosing between any, comparable, cmp.Ordered, and interfaces
| Constraint / Pattern | Allowed operations | Use when |
|---|---|---|
any |
Store, pass, return (no == or <) |
Queues, slices, pointer wrappers |
comparable |
==, !=, map keys (map[T]V) |
Deduplication, sets, caches |
cmp.Ordered |
<, <=, >, >=, == |
Min/max, sorting, ranges on numbers and strings |
| Regular interface (no generics) | Method calls (io.Reader, http.Handler) |
Callers vary by behavior rather than data type |
💡 Tip
Check slices (Sort, SortFunc, Contains, Clone, Compact) and maps (Keys, Values, Clone, Equal) before writing a custom generic helper. In Go 1.23+, slices.Sorted(maps.Keys(m)) sorts map keys in a single readable expression.
Common mistakes
- Replacing clean interfaces with generics: Writing
func ReadAll[R io.Reader](r R)adds noise without helping—acceptingr io.Readerdirectly is simpler and idiomatic. - Expecting slices or maps to satisfy
comparable: Slices, maps, and functions cannot be compared with==in Go, so they do not satisfycomparable. - Trying to put type parameters on struct methods: Only top-level functions and type definitions can declare
[T ...]; struct methods cannot introduce new type parameters of their own.
⚠ Warning
Do not introduce generics "just in case" when you only have one concrete type. Wait until you have two or more real types sharing the exact same data-structure algorithm.
What happens if you skip this
Without generics and slices/maps, codebases either accumulate duplicated per-type helpers or rely on any and discover type mismatches only when a production type assertion panics.
Related course: Go Intermediate.
About
Use type parameters with comparable and cmp.Ordered alongside Go's standard slices and maps packages. After this, you eliminate duplicate helpers without losing type safety.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 3 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.