Subscribe

Golang Tutorial 16: Generics

Type parameters and constraints in Go, a generic Map, Filter and Reduce, a typed TTL cache, the new generic methods in Go 1.27, and when a plain interface is still the better choice. Runnable examples and an exercise.

Golang Tutorial 16: Generics

Before Go 1.18, if you wanted a Filter for a slice of trades and another for a slice of strings, you wrote it twice or you used interface{} and type assertions everywhere. Generics fixed that. In this blog we will write a few generic functions, a typed cache, try the generic methods that arrived in Go 1.27, and then talk about when you should not use generics at all.

Level is intermediate. You need to know slices (Tutorial 9) and interfaces (Tutorial 11). I ran everything on Go 1.27.3. Generic methods need 1.27, everything else works on 1.21 or newer.

mkdir tut16 && cd tut16
go mod init example.com/tut16
mkdir -p cmd/basics cmd/cache cmd/methods cache

Type parameters

A generic function has a list of type parameters in square brackets before the normal parameters. Each one has a constraint, which says what types are allowed. any allows everything.

func Map[T, U any](in []T, f func(T) U) []U {
    out := make([]U, 0, len(in))
    for _, v := range in {
        out = append(out, f(v))
    }
    return out
}

T is the type of the input elements and U is the type of the output. When you call Map(trades, func(t Trade) string {...}), the compiler works out T = Trade and U = string from the arguments. You almost never write the types out by hand.

Filter and Reduce follow the same idea.

func Filter[T any](in []T, keep func(T) bool) []T {
    var out []T
    for _, v := range in {
        if keep(v) {
            out = append(out, v)
        }
    }
    return out
}

func Reduce[T, A any](in []T, start A, f func(A, T) A) A {
    acc := start
    for _, v := range in {
        acc = f(acc, v)
    }
    return acc
}

Constraints

any is fine as long as you only move values around. The moment you want to use + or < on a T, the compiler needs to know every allowed type supports it. That's what a constraint interface with a type list is for.

// Number is a constraint: any type whose underlying type is one of these.
type Number interface {
    ~int | ~int64 | ~float64
}

func Sum[T Number](in []T) T {
    var total T
    for _, v := range in {
        total += v
    }
    return total
}

The ~ actually matters more than it looks. For this example I keep money as integer paise in a named type, type Paise int64, so there's no float rounding. (The Zerodha charges post used float64 and rounding, this is the other way to do it.) When I tried Sum with a Number that had no tildes, the compiler said this.

./main.go:16:9: Paise does not satisfy Number (possibly missing ~ for int64 in Number)
./main.go:17:9: string does not satisfy Number (string missing in int | int64 | float64)

Nice error, it even guess the fix. Without ~, int64 means exactly int64. With ~int64 it means "any type whose underlying type is int64", so Paise is in. The second error is the one we want: Sum on strings is refused at compile time.

For ordering you don't need your own constraint. The standard library has cmp.Ordered, which covers integers, floats and strings.

func MaxOf[T cmp.Ordered](in ...T) T {
    m := in[0]
    for _, v := range in[1:] {
        m = max(m, v)
    }
    return m
}

Now use all of it together in cmd/basics/main.go (the package, imports and the functions above go in the same file).

type Paise int64 // money in paise, so no float rounding

type Trade struct {
    Symbol string
    Qty    int
    Price  Paise
}

func main() {
    trades := []Trade{
        {"INFY", 10, 152000},
        {"TCS", 2, 345050},
        {"INFY", 5, 151500},
        {"HDFCBANK", 8, 98000},
    }

    infy := Filter(trades, func(t Trade) bool { return t.Symbol == "INFY" })
    values := Map(infy, func(t Trade) Paise { return Paise(t.Qty) * t.Price })
    fmt.Println("INFY values:", values, "total:", Sum(values))

    symbols := Map(trades, func(t Trade) string { return strings.ToLower(t.Symbol) })
    fmt.Println("symbols:", symbols)

    qty := Reduce(trades, 0, func(acc int, t Trade) int { return acc + t.Qty })
    fmt.Println("total qty:", qty)

    fmt.Println(MaxOf(3, 9, 4), MaxOf("apple", "pear", "fig"), MaxOf(2.5, 1.5))
}
INFY values: [1520000 757500] total: 2277500
symbols: [infy tcs infy hdfcbank]
total qty: 25
9 pear 2.5

Before you write your own helpers, look at the slices and maps packages. slices.Index, slices.Contains, slices.SortFunc, slices.Sorted(maps.Keys(m)) are all generic and already tested. There is still no Map or Filter in the standard library, which is why people keep writing them.

A typed cache

This is where generics paid off most for me in this tutorial itself. A cache with a TTL, written once, used for any key and value type. The key needs comparable because it goes into a map.

// Package cache is a small typed in-memory cache with a TTL.
package cache

import (
    "sync"
    "time"
)

type entry[V any] struct {
    val     V
    expires time.Time
}

type Cache[K comparable, V any] struct {
    mu    sync.Mutex
    ttl   time.Duration
    items map[K]entry[V]
    now   func() time.Time
}

func New[K comparable, V any](ttl time.Duration) *Cache[K, V] {
    return &Cache[K, V]{ttl: ttl, items: make(map[K]entry[V]), now: time.Now}
}

func (c *Cache[K, V]) Set(k K, v V) {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.items[k] = entry[V]{val: v, expires: c.now().Add(c.ttl)}
}

// Get returns the value and true, or the zero value and false.
func (c *Cache[K, V]) Get(k K) (V, bool) {
    c.mu.Lock()
    defer c.mu.Unlock()
    e, ok := c.items[k]
    if !ok || c.now().After(e.expires) {
        delete(c.items, k)
        var zero V
        return zero, false
    }
    return e.val, true
}

// GetOrLoad returns a cached value or calls load and caches the result.
func (c *Cache[K, V]) GetOrLoad(k K, load func(K) (V, error)) (V, error) {
    if v, ok := c.Get(k); ok {
        return v, nil
    }
    v, err := load(k)
    if err != nil {
        return v, err
    }
    c.Set(k, v)
    return v, nil
}

func (c *Cache[K, V]) Len() int {
    c.mu.Lock()
    defer c.mu.Unlock()
    return len(c.items)
}

Two small thing. var zero V is how you get the zero value of a type parameter, there's no literal for it. And the now field is there so a test can move the clock without sleeping.

package main

import (
    "fmt"
    "time"

    "example.com/tut16/cache"
)

type Quote struct {
    Symbol string
    LTP    float64
}

func main() {
    quotes := cache.New[string, Quote](30 * time.Second)
    calls := 0
    load := func(sym string) (Quote, error) {
        calls++
        return Quote{Symbol: sym, LTP: 1520.5}, nil
    }

    for range 3 {
        q, _ := quotes.GetOrLoad("INFY", load)
        fmt.Printf("%s %.2f\n", q.Symbol, q.LTP)
    }
    fmt.Println("loader calls:", calls)

    // A different cache, different types, same code.
    hits := cache.New[int, []string](time.Minute)
    hits.Set(404, []string{"/old-link", "/favicon.ico"})
    paths, ok := hits.Get(404)
    fmt.Println(paths, ok)

    // hits.Set("404", nil) would not compile: cannot use "404" as int value
}
INFY 1520.50
INFY 1520.50
INFY 1520.50
loader calls: 1
[/old-link /favicon.ico] true

Here you do write the types out, cache.New[string, Quote], since there is no argument the compiler could infer them from. The code that uses the cache gets a Quote back, no type assertion. With the old map[string]interface{} version every Get needed .(Quote) and a check.

I also wrote two tests for it, one moving the fake clock past the TTL and one hammering it from 100 goroutines. Both pass with go test -race ./.... Testing gets its own post next, so I won't go into them here.

A warning about GetOrLoad: two goroutines that miss at the same time both call load. For a quote API that is wasted calls, for a slow database query under load it is the thundering herd. The caching strategies post covers the fixes (singleflight is the usual one).

Generic methods in Go 1.27

Up to Go 1.26, a method could use its type's parameters but couldn't add new ones. So you could not write list.Map(...) returning a list of a different type. Go 1.27 lifted that.

// Go 1.27: methods can have their own type parameters.
package main

import (
    "fmt"
    "strconv"
)

type List[T any] struct {
    items []T
}

func (l List[T]) Map[U any](f func(T) U) List[U] {
    out := List[U]{items: make([]U, 0, len(l.items))}
    for _, v := range l.items {
        out.items = append(out.items, f(v))
    }
    return out
}

func main() {
    nums := List[int]{items: []int{1, 2, 3}}
    strs := nums.Map(func(n int) string { return "#" + strconv.Itoa(n*10) })
    fmt.Println(strs.items)
}
[#10 #20 #30]

Its tied to the go line in go.mod. I set mine to go 1.26 to check, and got generic method requires go1.27 or later (-lang was set to go1.26; check go.mod). So a library that uses this forces every user onto 1.27.

But there's one limit worth knowing. Problem is, a generic method can't satisfy an interface. I tried to make Box[int] (same idea as List) satisfy an interface with a plain Map(func(int) int) Box[int] method and the compiler refused: have Map[U any](func(int) U) Box[U], want Map(func(int) int) Box[int]. Interfaces themselves still can't declare generic methods either.

When an interface is the better choice

Generics are for code that does the same thing to many types: containers, slice and map helpers, a cache. Interfaces are for code where different types do different things behind one method: an io.Writer that is a file or a buffer or a network connection, or a Store that is Postgres in production and a map in tests.

A quick check I like. If the function body calls methods on the value, an interface parameter is usually simpler. func Save(w io.Writer) reads better than func Save[W io.Writer](w W) and does the same job. If the body only stores, compares or moves values around, and the caller wants the exact type back, use a type parameter.

And don't make things generic "in case". A function used for one type is easier to read without the brackets. Basically I would wait until the second or third copy before reaching for a type parameter.

Exercise

Write GroupBy[T any, K comparable](in []T, key func(T) K) map[K][]T and use it to group orders by symbol. Then write SortedKeys for any map with ordered keys, and print the groups in key order. Hint for the second one: slices.Sorted(maps.Keys(m)) does most of the work.

With orders TCS 2, INFY 10, TCS 1, HDFCBANK 8 my version printed this.

HDFCBANK [{HDFCBANK 8}]
INFY [{INFY 10}]
TCS [{TCS 2} {TCS 1}]