I still remember the first Go service I was proud of. Clean folder structure, tests, the whole thing. Then I opened the utils package and found SumInts, SumInt64s, SumFloat64s, and a FilterUsers that was a copy of FilterOrders with two words changed.
I told myself it was fine. Go is verbose, right? That is just how it is.
It was not fine. Three months later a bug in the filter logic had to be fixed in four places, and of course I missed one.
That is the problem generics solve. Not “make Go look like TypeScript”, just: write the algorithm once, keep the compiler checking your types, stop maintaining copies of the same twenty lines.
Generics landed in Go 1.18. Since Go 1.21 the standard library also gives us slices, maps, and cmp, which quietly deleted half the helper packages I used to write.
The copy-paste phase, and what it actually costs
Here is the honest before picture:
func SumInts(values []int) int {
var total int
for _, v := range values {
total += v
}
return total
}
func SumFloat64s(values []float64) float64 {
var total float64
for _, v := range values {
total += v
}
return total
}
Nothing is wrong with either function. The problem is that there are two of them, and tomorrow there will be four. Someone will add a SumInt32 for a report, get the loop condition slightly off, and nobody will notice for a year.
The old escape hatch was interface{} plus reflection or type assertions. I have written that code. It compiles, it runs, and it panics in production on a type you did not think about.
Generics let you say the thing you actually mean:
func Sum[T int | float64](values []T) T {
var total T
for _, v := range values {
total += v
}
return total
}
func main() {
fmt.Println(Sum([]int{1, 2, 3})) // 6
fmt.Println(Sum([]float64{1.5, 2.25})) // 3.75
}
One function. Two call sites. And if I pass a []string, it does not compile, which is exactly the feedback I want.
Reading a generic signature out loud
[T int | float64] is just a list of type parameters. Read it as: “for any type T that is either int or float64”.
func Name[T Constraint](param T) T {
// ...
}
A few things worth internalising, because they explain most of the confusing errors you will see:
The compiler checks every type argument against the constraint when you build. Not at runtime. So a wrong type is a build failure, not a 3 a.m. alert.
Inside the function you only get the operations the constraint promises. With int | float64 that includes +, <, and friends. With any you can assign values and compare them to nil, and that is about it. This trips people up constantly. You cannot add two Ts under any, and the error message is not shy about telling you so.
Constraints without the jargon
A constraint is a set of types. That is the whole idea.
any means every type. Useful for containers where you never inspect the values:
func First[T any](items []T) (T, bool) {
var zero T
if len(items) == 0 {
return zero, false
}
return items[0], true
}
Notice var zero T instead of return nil. T might be int, so nil makes no sense. Declaring the zero value is the idiom, and the bool tells the caller whether anything was actually there. It is a small pattern, but once it clicks you stop fighting the compiler.
comparable is the one for map keys and ==:
func Contains[T comparable](items []T, target T) bool {
for _, item := range items {
if item == target {
return true
}
}
return false
}
func Keys[K comparable, V any](m map[K]V) []K {
keys := make([]K, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return keys
}
Numbers, strings, booleans, pointers, channels, structs made of those. Slices, maps, and functions are not comparable, so they will not fit here. I have watched a teammate spend twenty minutes on that error before remembering it.
When you have a family of types, name the constraint instead of repeating the union at every call site:
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64
}
func Average[T Number](values []T) float64 {
if len(values) == 0 {
return 0
}
var total T
for _, v := range values {
total += v
}
return float64(total) / float64(len(values))
}
That tilde, and why your UserID did not compile
This one bit me. I had a type UserID int64, wrote Average(ids), and got a constraint error that made no sense at first read.
The reason: int64 in a constraint means exactly int64. Your UserID is a different type that happens to be built on top of it. Putting ~ in front means “int64 or anything whose underlying type is int64”:
type UserID int64
// ~int64 in Number is what makes this legal
fmt.Println(Average([]UserID{10, 20, 30})) // 20
My rule now: if the function is generic infrastructure rather than a one-off, add the tilde. It costs nothing and it saves somebody an afternoon.
Constraints can also ask for behaviour instead of an underlying type:
type Stringer interface {
String() string
}
func JoinStrings[T Stringer](items []T, sep string) string {
parts := make([]string, 0, len(items))
for _, item := range items {
parts = append(parts, item.String())
}
return strings.Join(parts, sep)
}
This is the case where generics genuinely beat interface{}: the method call is checked once at compile time, and there is no dynamic type assertion hiding in the loop.
Type inference is better than you think
You almost never write the brackets by hand. Go reads the types from your arguments:
Sum([]int{1, 2, 3}) // T is int
Map([]int{1, 2, 3}, func(v int) string { ... }) // T is int, U is string
It only stops working when there is nothing to read:
// no argument mentions T, so be explicit
stack := NewStack[int]()
Which gives you a design rule I now follow without thinking: if a type parameter can appear in the parameter list, put it there. Types that only show up in the return type force callers to spell everything out, and they will quietly resent you for it.
The helpers I actually keep
After a few projects, my generic toolbox got small. Almost everything else came from the standard library eventually.
func Map[T, U any](in []T, fn func(T) U) []U {
out := make([]U, 0, len(in))
for _, v := range in {
out = append(out, fn(v))
}
return out
}
func Filter[T any](in []T, keep func(T) bool) []T {
out := make([]T, 0, len(in))
for _, v := range in {
if keep(v) {
out = append(out, v)
}
}
return out
}
func Reduce[T, A any](in []T, initial A, fn func(A, T) A) A {
acc := initial
for _, v := range in {
acc = fn(acc, v)
}
return acc
}
And it does make calling code nicer:
type Order struct {
ID string
Total float64
Status string
}
orders := []Order{
{ID: "A1", Total: 120.50, Status: "paid"},
{ID: "A2", Total: 80.00, Status: "pending"},
{ID: "A3", Total: 200.00, Status: "paid"},
}
paid := Filter(orders, func(o Order) bool { return o.Status == "paid" })
ids := Map(paid, func(o Order) string { return o.ID })
revenue := Reduce(paid, 0.0, func(sum float64, o Order) float64 {
return sum + o.Total
})
[A1 A3] and 320.5. No type assertions, no map[string]interface{} floating around.
And the one I reach for constantly:
func GroupBy[T any, K comparable](in []T, key func(T) K) map[K][]T {
groups := make(map[K][]T)
for _, v := range in {
k := key(v)
groups[k] = append(groups[k], v)
}
return groups
}
GroupBy is the one I use most in real work. Grouping by status, by tenant, by day. Before generics that was a new function per type, or a map[string][]interface{} that ruined every caller downstream.
Generic types are the same idea in a different shape
Functions are not special. Types take parameters too, and this is where generics start feeling worth the syntax.
type Set[T comparable] map[T]struct{}
func NewSet[T comparable](values ...T) Set[T] {
s := make(Set[T], len(values))
for _, v := range values {
s.Add(v)
}
return s
}
func (s Set[T]) Add(v T) { s[v] = struct{}{} }
func (s Set[T]) Remove(v T) { delete(s, v) }
func (s Set[T]) Len() int { return len(s) }
func (s Set[T]) Has(v T) bool {
_, ok := s[v]
return ok
}
struct{} costs zero bytes, so this is exactly the map you would have written by hand, just reusable.
A stack, because interviewers love them and so do parsers:
type Stack[T any] struct {
items []T
}
func NewStack[T any]() *Stack[T] { return &Stack[T]{} }
func (s *Stack[T]) Push(v T) {
s.items = append(s.items, v)
}
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
last := len(s.items) - 1
v := s.items[last]
s.items = s.items[:last]
return v, true
}
Stack[Order] and Stack[*User] both work, with no reflection and no casting at the call site.
Stop rewriting what Go already ships
I want to save you some time. Before you add a SliceUtils file to your repo, check these:
import (
"cmp"
"maps"
"slices"
)
numbers := []int{5, 2, 9, 1}
slices.Sort(numbers)
fmt.Println(slices.Contains(numbers, 5)) // true
fmt.Println(slices.Max(numbers)) // 9
names := []string{"budi", "ani", "candra"}
slices.SortFunc(names, func(a, b string) int {
return cmp.Compare(strings.ToLower(a), strings.ToLower(b))
})
There is also slices.DeleteFunc, slices.Compact, slices.Clone, slices.BinarySearch, maps.Clone, maps.Copy, and the min/max builtins. Since Go 1.21 these are tested, optimised, and maintained by people who think about edge cases more than I do. My own helper now has to earn its place.
The walls you will hit
Nobody warns you about these in the tutorial, so here they are in advance.
Methods cannot have their own type parameters. This one hurts:
type Repo struct{}
// compile error
func (r Repo) Find[T any](id string) (T, error) { ... }
The workaround is a generic function that takes the receiver, or making the type itself generic. Not elegant, but workable.
You cannot type-switch on a type parameter. If you catch yourself writing any(v).(type) inside a generic function, that is usually a signal that you wanted an interface in the first place.
nil comparisons need care. if v == nil does not compile for an unconstrained T. You can box it with any(v) == nil, but stop and ask whether any was the right constraint.
No constants as type parameters. No Array[T, N int]. Fixed-size arrays cannot be parameterised by length, so vector-style code still needs code generation.
No operators from method constraints. You cannot require + through an interface. Operators only come from union constraints over underlying types.
Pointer receivers and constraints do not always line up. If String() is defined on *T and your type argument is T, it does not satisfy Stringer. Pass *T instead.
About performance, honestly
Here is the part where blog posts usually promise a 10x speedup. I will not.
Go does not generate a fully separate copy of your function for every concrete type, the way C++ templates or Rust do. It compiles by GC shape: types with the same memory layout share an instantiation, and type-specific operations may go through a dictionary. So you get most of the type safety and usually avoid the boxing that interface{} imposes, but you do not get all the constant-folding magic a specialised copy would give you.
In practice: generic code over int or string is normally in the same ballpark as hand-written code. If the function is on a hot path, measure it. Not because generics are slow, but because guessing about performance is how we ended up with micro-optimised code that made things worse.
func BenchmarkSumInts(b *testing.B) {
values := make([]int, 1024)
for i := range values {
values[i] = i
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = Sum(values)
}
}
When I still write an interface
I like generics. I reach for them less than you would expect.
If different types need different implementations of the same behaviour, that is polymorphism, and interfaces are the right tool. If callers should be able to add their own implementations, interfaces again. If I need to hold values of different concrete types in one variable, also interfaces.
The line I use: generics describe shapes, interfaces describe behaviour. When a constraint grows to fifteen methods and the function calls one of them, I delete the type parameter and go back to an interface. Every single time, the code gets easier to read.
A refactor from a real project
We had pagination duplicated per model. Two functions, identical math, different types:
func PaginateUsers(users []User, page, size int) []User { ... }
func PaginateOrders(orders []Order, page, size int) []Order { ... }
It became this:
func Paginate[T any](items []T, page, size int) []T {
if page < 1 || size < 1 {
return nil
}
start := (page - 1) * size
if start >= len(items) {
return nil
}
end := start + size
if end > len(items) {
end = len(items)
}
return items[start:end]
}
One implementation, one set of tests, one place to fix the off-by-one when we eventually got it wrong. That, to me, is the real selling point. Not clever abstractions. Fewer places for the same bug to hide.
A short checklist before you add [T any]
I run through this every time now, and it has saved me from a few clever-but-unreadable signatures:
- Would an interface do this with less head-scratching? Then use the interface.
- Does the type parameter appear in the arguments, so inference works?
- Did I add
~so named types still fit? - Am I returning
var zero Trather thannil? - Does
slices,maps, orcmpalready do this? - Is this on a hot path, and did I benchmark?
Closing thoughts
Generics did not change how I write Go. They removed a specific kind of pain: the duplicate helper, the interface{} cast, the map[string]interface{} that nobody wants to touch six months later.
Write It Once, Then Forget About It
Start with one duplicated function. Turn it generic, add a tilde to the constraint, watch type inference do its thing. If a signature needs two sentences to explain, that is your signal to step back and use an interface. The best generic code is the code a reader never notices. They just see a function that works for their type and move on, which is honestly the highest compliment Go code can get.
And if your repo still has three versions of Filter, go delete two of them. It feels great. 🐹
Comments
comments powered by Disqus