Generics, Constraints, and slices/maps Packages
Write type-safe generic helpers with comparable and cmp.Ordered, and reuse standard slices and maps utilities. After this, you avoid boilerplate without overusing any.
Course content
Sign in to save your progress.
-
Interfaces and Standard Abstractions
-
Interfaces Are Satisfied Implicitly
-
Read and Stream With io.Reader and io.Writer
-
-
-
Context, Timeouts, and Cancellation
-
Use context.Context for Deadlines and Cancellation
-
Set Timeouts on HTTP Clients and Server Handlers
-
-
-
Goroutines, Channels, and Coordination
-
Run Concurrent Work Safely With sync.WaitGroup
-
Coordinate Pipelines and Timeouts With Channels and select
-
-
-
Structured Logging and Databases
-
Write Structured JSON Logs With log/slog
-
Query Relational Data Safely With database/sql
-
-
-
Middleware and Production-Ready Services
-
Wrap HTTP Handlers With Middleware
-
Build a Multi-Route Service With Graceful Shutdown
-
-
-
Generics, Transactions, Timers, and Test Doubles
-
Generics, Constraints, and slices/maps Packages
-
SQL Transactions and Connection Pool Limits
-
Timers, Tickers, and Avoiding time.After Leaks
-
Testing With Interface Fakes, t.TempDir, and testdata
-
-
Before Go 1.18, writing a reusable helper like Dedupe or MaxOf forced an uncomfortable choice: copy-paste the same 15-line loop for []int, []string, and []int64, or accept []any and give up compile-time type checks. Go generics give you type-safe parameterized functions—and the standard library's cmp, slices, and maps packages eliminate most hand-written collection code entirely.
Skip ahead
If you already write type-parameterized helpers with comparable and cmp.Ordered, use slices and maps, and know when an interface is cleaner than a generic, continue to "SQL Transactions and Connection Pool Limits."
Experiment 1: Writing generic functions with comparable and cmp.Ordered
Go requires every type parameter [T Constraint] to declare what operations T supports up front so the compiler can verify the function once—without waiting for callers:
comparable: Guarantees==and!=, meaningTcan be used as amap[T]Vkey.cmp.Ordered: Guarantees ordering comparisons (<,<=,>,>=)—all integer, float, and string types.
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)
}
deduped sorted: [1 2 3]
max string: rust
sorted keys: [a b]
Notice that at every call site—Dedupe([]int{...}) and MaxOf("go", "rust")—Go infers T automatically from the arguments so callers rarely have to write Dedupe[int](...) explicitly.
Experiment 2: Generic container types (like a thread-safe or typed cache)
Generics also shine on reusable data structures where only the stored type varies:
type Set[T comparable] map[T]struct{}
func (s Set[T]) Add(v T) { s[v] = struct{}{} }
func (s Set[T]) Has(v T) bool { _, ok := s[v]; return ok }
Notice one Go rule to remember: a type can declare [T comparable] and its methods can use T, but a method cannot introduce a brand-new extra type parameter of its own (for example func (s Set[T]) Map[U any](...) is not allowed—make that a package-level function Map[T, U](...) instead).
Experiment 3: Reach for slices and maps before writing your own
Most slice and map helpers you used to write by hand already ship in the standard library:
slices.Sort(s),slices.SortFunc(s, func(a, b User) int { return cmp.Compare(a.ID, b.ID) })slices.Contains(s, target),slices.Index(s, target),slices.Clone(s),slices.Compact(s)slices.Sorted(maps.Keys(m)),maps.Clone(m),maps.Equal(a, b)
When to use an interface instead of generics
If a function works on different types that implement different behaviors (reading from a file vs. a network socket vs. an in-memory buffer), use a plain interface (r io.Reader). Writing func Parse[R io.Reader](r R) adds noise with zero benefit. Save generics for data structures and algorithms where the exact same code runs over different value types.
Common mistakes
- Passing a slice or struct-with-slice to
[T comparable]: Slices, maps, and functions do not support==, so they fail to satisfycomparable. - Overusing generics when only one type exists: Wait until you have two or more real types sharing identical logic before parameterizing.
- Using
slices.Compacton an unsorted slice:slices.Compactonly removes consecutive duplicates (like Unixuniq)—sort first or use a map-basedDedupe.
💡 Tip
cmp.Or(os.Getenv("PORT"), cfg.Port, "8080") (added in Go 1.22) returns the first non-zero value from any number of comparable arguments—a clean one-liner for config fallbacks.
What happens if you skip this step
Without generics and the standard slices/maps packages, projects either pile up copy-pasted per-type utility functions or fall back to any and hit runtime type-assertion panics.
Why does func Print[W io.Writer](w W, msg string) offer no real advantage over func Print(w io.Writer, msg string)?
About
Write type-safe generic helpers with comparable and cmp.Ordered, and reuse standard slices and maps utilities. After this, you avoid boilerplate without overusing any.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.