typestar

Generics in Go

Type parameters and constraint interfaces.

type Number interface {
    ~int | ~int64 | ~float64
}

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

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

How it works

  1. A constraint interface unions the allowed types.
  2. ~int includes types whose underlying type is int.
  3. Map[T, U any] transforms between element types.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
310
Tokens
108
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 59 seconds.

Type this snippet

Step 1 of 4 in Generics, step 13 of 19 in Interfaces & generics.

← Previous Next →

Generics in other languages