Programming languages · Advanced · 25 min
Write generic functions and types in Go
By Padding · Updated 18 Nov 2026
Debian (golang:1.27 image) · Go 1.27.4
You will replace three copies of a slice filter with one generic Go 1.27 function, then write constrained helpers, a custom constraint with ~, a generic Set type with an iterator and a generic method, and learn when the standard library or plain code is the better choice.
On this page
Generics let one Go function or type work with many element types while the compiler still checks every call. They arrived in Go 1.18, and each release since has filled in more: the cmp, slices, maps and iter packages, range-over-function iterators in Go 1.23, and in Go 1.27 generic methods, where a method declares type parameters of its own.
You start with a problem generics solve well: the same filter loop written three times for three element types. You fold the copies into one function, then learn what a constraint is by asking the compiler for == and > on a type parameter. From there you write your own constraint, build a small Set[T] package with an iterator and a generic method, and then delete code the standard library already provides. The last step is about restraint: most Go code should not be generic, and you finish with a short test for telling which is which.
The example uses an amount type in kobo, the smallest unit of the Nigerian naira. Storing money as whole minor units (kobo, cents, pesewas) rather than floats is good practice in any currency, and it is a natural case for a named type built on int64.
Everything lives in ~/generics-demo, one module with a main package and a set package.
Step 1 · Create the module and the three copies
Make the folder and a module for it:
mkdir -p ~/generics-demo
cd ~/generics-demo
go mod init example.com/generics
go mod edit -go=1.27.0Since Go 1.26, go mod init writes the previous minor version into go.mod (go 1.26.0 with Go 1.27.4), and the generic methods later in this tutorial need language version 1.27, so go mod edit raises it.
Create main.go with the starting point: three filter helpers that differ only in their element type. One keeps even numbers, one drops blank city names, one keeps paid orders:
cat > main.go <<'GO'
package main
import (
"fmt"
"strings"
)
type Order struct {
ID string
Paid bool
}
func filterInts(s []int, keep func(int) bool) []int {
var out []int
for _, v := range s {
if keep(v) {
out = append(out, v)
}
}
return out
}
func filterStrings(s []string, keep func(string) bool) []string {
var out []string
for _, v := range s {
if keep(v) {
out = append(out, v)
}
}
return out
}
func filterOrders(s []Order, keep func(Order) bool) []Order {
var out []Order
for _, v := range s {
if keep(v) {
out = append(out, v)
}
}
return out
}
func main() {
nums := []int{3, 8, 15, 22, 41}
cities := []string{"Lagos", "", "Nairobi", " ", "Accra"}
orders := []Order{{"A1", true}, {"A2", false}, {"A3", true}}
fmt.Println(filterInts(nums, func(n int) bool { return n%2 == 0 }))
fmt.Println(filterStrings(cities, func(c string) bool { return strings.TrimSpace(c) != "" }))
fmt.Println(filterOrders(orders, func(o Order) bool { return o.Paid }))
}
GO
go run .Before generics, the usual ways out were these copies, a code generator, or a function over []any that loses type checking and forces a type assertion on every result. The copies are the most honest of the three, but a bug fixed in one is still there in the other two.
Check it worked
go mod init prints go: creating new go.mod: module example.com/generics, and after the edit go.mod shows a go 1.27.0 line. go run . prints [8 22], [Lagos Nairobi Accra] and [{A1 true} {A3 true}] on three lines.
Step 2 · Replace the copies with one generic function
Put the loop in its own file, with a type parameter in square brackets after the function name:
cd ~/generics-demo
cat > filter.go <<'GO'
package main
// Filter returns a new slice holding the elements of s for which keep
// returns true. It works for a slice of any element type.
func Filter[T any](s []T, keep func(T) bool) []T {
var out []T
for _, v := range s {
if keep(v) {
out = append(out, v)
}
}
return out
}
GO[T any] declares a type parameter named T. any is its constraint: the set of types T may be. any allows every type, which is enough here, because the body only copies values of type T around and never compares or adds them.
Now rewrite main.go without the three copies. The calls drop the type suffix from the name; the last one passes the type argument explicitly to show that form:
cat > main.go <<'GO'
package main
import (
"fmt"
"strings"
)
type Order struct {
ID string
Paid bool
}
func main() {
nums := []int{3, 8, 15, 22, 41}
cities := []string{"Lagos", "", "Nairobi", " ", "Accra"}
orders := []Order{{"A1", true}, {"A2", false}, {"A3", true}}
fmt.Println(Filter(nums, func(n int) bool { return n%2 == 0 }))
fmt.Println(Filter(cities, func(c string) bool { return strings.TrimSpace(c) != "" }))
fmt.Println(Filter[Order](orders, func(o Order) bool { return o.Paid }))
}
GO
go run .
go vet ./...In the first two calls the compiler infers T from the arguments: nums is a []int, so T is int. Inference is the normal style. Write `FilterOrder only when there is nothing to infer from, such as a call with no arguments of type `T.
Type checking is as strict as with the old copies. Passing func(s string) bool alongside nums fails at compile time with a message like type func(s string) bool ... does not match inferred type func(int) bool for func(T) bool.
Check it worked
The output is the same three lines as before, and go vet ./... prints nothing. main.go no longer contains filterInts, filterStrings or filterOrders.
Step 3 · Constrain type parameters with comparable and cmp.Ordered
A body can only use operations that every type in the constraint supports. any includes slices, maps and functions, which cannot be compared with ==, and structs, which cannot be ordered with >. Two constraints cover the common cases:
comparableis built in. Its type set is the types that support==and!=: numbers, strings, booleans, pointers, channels, and arrays and structs made only of comparable parts.cmp.Orderedfrom the standard library is the types that support<,<=,>and>=: integers, floats and strings.
Create constraints.go with one of each:
cd ~/generics-demo
cat > constraints.go <<'GO'
package main
import "cmp"
// Index returns the position of the first element of s equal to target,
// or -1 if there is none. == needs a comparable type.
func Index[T comparable](s []T, target T) int {
for i, v := range s {
if v == target {
return i
}
}
return -1
}
// Max returns the largest element of s. The bool is false when s is empty.
// > needs an ordered type.
func Max[T cmp.Ordered](s []T) (T, bool) {
var zero T
if len(s) == 0 {
return zero, false
}
m := s[0]
for _, v := range s[1:] {
if v > m {
m = v
}
}
return m, true
}
GOvar zero T is how generic code spells "the zero value of whatever T is": 0, "" or an empty struct. Max returns it with false for an empty slice instead of panicking.
Replace main.go to call both:
cat > main.go <<'GO'
package main
import (
"fmt"
"strings"
)
type Order struct {
ID string
Paid bool
}
func main() {
nums := []int{3, 8, 15, 22, 41}
cities := []string{"Lagos", "", "Nairobi", " ", "Accra"}
orders := []Order{{"A1", true}, {"A2", false}, {"A3", true}}
fmt.Println(Filter(nums, func(n int) bool { return n%2 == 0 }))
fmt.Println(Filter(cities, func(c string) bool { return strings.TrimSpace(c) != "" }))
fmt.Println(Filter(orders, func(o Order) bool { return o.Paid }))
fmt.Println(Index(cities, "Nairobi"), Index(orders, Order{"A2", false}), Index(nums, 99))
fmt.Println(Max(nums))
fmt.Println(Max([]float64{2.5, 9.75, 4}))
fmt.Println(Max(cities))
fmt.Println(Max([]int{}))
}
GO
go run .Order works with Index because both its fields are comparable. A struct with a slice field, such as Items []string, would not: the call fails with ... does not satisfy comparable.
Now see what the constraints buy you. In constraints.go, change [T comparable] to [T any] and [T cmp.Ordered] to [T comparable], then build:
go build ./...The compiler rejects both bodies before any caller exists. It also reports "cmp" imported and not used, because nothing in the file mentions cmp.Ordered any more:
./constraints.go:3:8: "cmp" imported and not used
./constraints.go:9:6: invalid operation: v == target (incomparable types in type set)
./constraints.go:25:6: invalid operation: v > m (type parameter T cannot use operator >)Change both constraints back and run go build ./... again; it prints nothing.
Check it worked
go run . prints the three filter lines, then 2 1 -1, 41 true, 9.75 true, Nairobi true and 0 false. With the loosened constraints you saw both invalid operation errors, and after restoring them go build ./... is silent.
Step 4 · Write your own constraint with ~
A constraint is an interface. Besides methods, it can list types joined with |, which makes its type set exactly those types. Writing ~int64 instead of int64 means "every type whose underlying type is int64", which includes named types such as Kobo below.
Create number.go:
cd ~/generics-demo
cat > number.go <<'GO'
package main
import "fmt"
// Number is a constraint: its type set is every type whose underlying
// type is int, int64 or float64.
type Number interface {
~int | ~int64 | ~float64
}
// Sum adds up the elements of s.
func Sum[T Number](s []T) T {
var total T
for _, v := range s {
total += v
}
return total
}
// Kobo is an amount of money in kobo; 100 kobo make one naira.
type Kobo int64
func (k Kobo) String() string {
return fmt.Sprintf("NGN %d.%02d", k/100, k%100)
}
GO+= is allowed in Sum because every type in Number's type set supports it. The result keeps its type: Sum of a []Kobo is a Kobo, so it prints with the String method instead of as a bare number.
Add four lines to the end of main, so main.go becomes:
cat > main.go <<'GO'
package main
import (
"fmt"
"strings"
)
type Order struct {
ID string
Paid bool
}
func main() {
nums := []int{3, 8, 15, 22, 41}
cities := []string{"Lagos", "", "Nairobi", " ", "Accra"}
orders := []Order{{"A1", true}, {"A2", false}, {"A3", true}}
fmt.Println(Filter(nums, func(n int) bool { return n%2 == 0 }))
fmt.Println(Filter(cities, func(c string) bool { return strings.TrimSpace(c) != "" }))
fmt.Println(Filter(orders, func(o Order) bool { return o.Paid }))
fmt.Println(Index(cities, "Nairobi"), Index(orders, Order{"A2", false}), Index(nums, 99))
fmt.Println(Max(nums))
fmt.Println(Max([]float64{2.5, 9.75, 4}))
fmt.Println(Max(cities))
fmt.Println(Max([]int{}))
prices := []Kobo{150000, 2550, 99}
fmt.Println(Sum(nums), Sum([]float64{0.5, 0.25}))
fmt.Println(Sum(prices))
fmt.Println(Max(prices))
}
GO
go run .Max(prices) also works, because cmp.Ordered is written with ~ terms too.
To see what the tilde does, change ~int64 to int64 in number.go and run go build ./.... The compiler points at the Sum(prices) call:
./main.go:30:17: Kobo does not satisfy Number (possibly missing ~ for int64 in Number)Put the ~ back. One more rule: an interface that lists types can only be used as a constraint. var n Number fails with cannot use type Number outside a type constraint. If you want a variable that holds "some number", that is a job for a concrete type, not a type set.
Check it worked
The last three lines of output are 89 0.75, NGN 1526.49 and NGN 1500.00 true. Without the tilde you saw possibly missing ~ for int64 in Number, and with it restored go build ./... prints nothing.
Step 5 · Build a generic Set type
Types take type parameters too. A set of unique values is a map with empty-struct values; wrapping it in a generic type gives it a clear API. Create the set package:
cd ~/generics-demo
mkdir -p set
cat > set/set.go <<'GO'
// Package set provides a set of unique values of any comparable type.
package set
// Set holds unique values of type T. The zero value is an empty set
// ready to use.
type Set[T comparable] struct {
items map[T]struct{}
}
// New returns a set holding the given values.
func New[T comparable](values ...T) *Set[T] {
s := &Set[T]{}
for _, v := range values {
s.Add(v)
}
return s
}
// Add puts v in the set. Adding a value that is already there does nothing.
func (s *Set[T]) Add(v T) {
if s.items == nil {
s.items = make(map[T]struct{})
}
s.items[v] = struct{}{}
}
// Remove takes v out of the set.
func (s *Set[T]) Remove(v T) {
delete(s.items, v)
}
// Has reports whether v is in the set.
func (s *Set[T]) Has(v T) bool {
_, ok := s.items[v]
return ok
}
// Len returns the number of values in the set.
func (s *Set[T]) Len() int {
return len(s.items)
}
GOThe constraint is comparable because map keys must be. The methods use Set[T] as the receiver type, and T inside them means the same T the set was made with. A Set[string] and a Set[int] are different types; you cannot pass one where the other is expected.
Add creates the map on first use, so var s set.Set[int] works without calling New. Reading or deleting from a nil map is already safe in Go, so Has, Len and Remove need no such check.
Add tests for both ways of making a set:
cat > set/set_test.go <<'GO'
package set
import "testing"
func TestSetStrings(t *testing.T) {
s := New("Lagos", "Accra", "Lagos")
if s.Len() != 2 {
t.Fatalf("Len() = %d, want 2", s.Len())
}
if !s.Has("Accra") || s.Has("Kigali") {
t.Fatalf("Has gave the wrong answer")
}
s.Remove("Accra")
if s.Has("Accra") || s.Len() != 1 {
t.Fatalf("Remove did not remove Accra")
}
}
func TestZeroValueSet(t *testing.T) {
var s Set[int]
s.Add(7)
s.Add(7)
if s.Len() != 1 || !s.Has(7) {
t.Fatalf("zero-value set: Len() = %d, Has(7) = %v", s.Len(), s.Has(7))
}
}
GO
go test -v ./set/In New("Lagos", "Accra", "Lagos") the compiler infers T as string from the arguments. With no arguments there is nothing to infer from, so an empty set is written set.New[int]().
Check it worked
go test -v ./set/ prints --- PASS: TestSetStrings and --- PASS: TestZeroValueSet, then ok example.com/generics/set followed by a time.
Step 6 · Range over the set with an iterator and a generic method
Callers need to loop over the values without reaching into the map. iter.Seq[T] is the standard type for that: a function that takes a yield callback and calls it once per value. Since Go 1.23 a for ... range loop can range over such a function directly.
Go 1.27 also allows generic methods: a method can declare its own type parameters after its name. That fits a Map operation, which turns a Set[T] into a set of some other type U. Before Go 1.27 this had to be a top-level function, set.Map(s, f). Put both in set/iter.go:
cd ~/generics-demo
cat > set/iter.go <<'GO'
package set
import "iter"
// All returns an iterator over the values in s, in no fixed order.
func (s *Set[T]) All() iter.Seq[T] {
return func(yield func(T) bool) {
for v := range s.items {
if !yield(v) {
return
}
}
}
}
// Map returns a new set holding f(v) for every v in s. Map is a generic
// method: it declares its own type parameter U, which needs Go 1.27.
func (s *Set[T]) Map[U comparable](f func(T) U) *Set[U] {
out := New[U]()
for v := range s.All() {
out.Add(f(v))
}
return out
}
GOyield returns false when the loop body stops early with break or return. The iterator must stop then. If it ignores the result and calls yield again, the program panics with range function continued iteration after function for loop body returned false.
Generic methods have one limit to know about: interface methods cannot have type parameters, and a generic method does not satisfy an interface method. Keep Map as a convenience on the concrete type, not as part of an interface you expect other types to implement.
Test the iterator, the early stop and Map:
cat > set/iter_test.go <<'GO'
package set
import (
"slices"
"testing"
)
func TestAllVisitsEveryValue(t *testing.T) {
got := slices.Sorted(New(3, 1, 2).All())
if !slices.Equal(got, []int{1, 2, 3}) {
t.Fatalf("All() gave %v, want [1 2 3]", got)
}
}
func TestAllStopsWhenTheLoopBreaks(t *testing.T) {
seen := 0
for range New("a", "b", "c", "d").All() {
seen++
if seen == 2 {
break
}
}
if seen != 2 {
t.Fatalf("loop ran %d times, want 2", seen)
}
}
func TestMap(t *testing.T) {
lengths := New("Lagos", "Accra", "Kigali").Map(func(c string) int { return len(c) })
got := slices.Sorted(lengths.All())
if !slices.Equal(got, []int{5, 6}) {
t.Fatalf("Map gave %v, want [5 6]", got)
}
}
GO
go test ./set/Map iteration order in Go is deliberately unpredictable, so the tests sort with slices.Sorted, which takes any iter.Seq of an ordered type. Use the set from main too: add the import example.com/generics/set and slices, and these lines at the end of main. The full file is:
cat > main.go <<'GO'
package main
import (
"fmt"
"slices"
"strings"
"example.com/generics/set"
)
type Order struct {
ID string
Paid bool
}
func main() {
nums := []int{3, 8, 15, 22, 41}
cities := []string{"Lagos", "", "Nairobi", " ", "Accra"}
orders := []Order{{"A1", true}, {"A2", false}, {"A3", true}}
fmt.Println(Filter(nums, func(n int) bool { return n%2 == 0 }))
fmt.Println(Filter(cities, func(c string) bool { return strings.TrimSpace(c) != "" }))
fmt.Println(Filter(orders, func(o Order) bool { return o.Paid }))
fmt.Println(Index(cities, "Nairobi"), Index(orders, Order{"A2", false}), Index(nums, 99))
fmt.Println(Max(nums))
fmt.Println(Max([]float64{2.5, 9.75, 4}))
fmt.Println(Max(cities))
fmt.Println(Max([]int{}))
prices := []Kobo{150000, 2550, 99}
fmt.Println(Sum(nums), Sum([]float64{0.5, 0.25}))
fmt.Println(Sum(prices))
fmt.Println(Max(prices))
visited := set.New("Lagos", "Accra", "Lagos", "Kigali")
for city := range visited.All() {
if strings.HasPrefix(city, "K") {
fmt.Println("found", city)
break
}
}
fmt.Println(visited.Len(), slices.Sorted(visited.All()))
fmt.Println(slices.Sorted(visited.Map(strings.ToUpper).All()))
}
GO
go run .visited.Map(strings.ToUpper) infers U as string from the function you pass. Mapping to len would give a *Set[int] instead.
Check it worked
go test ./set/ prints ok example.com/generics/set; with -v you see five --- PASS lines. go run . ends with found Kigali, 3 [Accra Kigali Lagos] and [ACCRA KIGALI LAGOS]. The duplicate Lagos was stored once.
Step 7 · Let slices and maps do the work
Much of what you have written already exists. The slices package has generic Index, Contains, Max, Min, Sort, Clone, Sorted and more; maps has Keys, Values, Clone and Collect. Standard library code is tested, documented and familiar to every Go reader, so prefer it.
maps.Keys returns an iter.Seq over a map's keys, which is exactly what All does by hand. Replace set/iter.go:
cd ~/generics-demo
cat > set/iter.go <<'GO'
package set
import (
"iter"
"maps"
)
// All returns an iterator over the values in s, in no fixed order.
func (s *Set[T]) All() iter.Seq[T] {
return maps.Keys(s.items)
}
// Map returns a new set holding f(v) for every v in s. Map is a generic
// method: it declares its own type parameter U, which needs Go 1.27.
func (s *Set[T]) Map[U comparable](f func(T) U) *Set[U] {
out := New[U]()
for v := range s.All() {
out.Add(f(v))
}
return out
}
GO
go test ./set/Your Index and Max have direct replacements too, so delete constraints.go and use slices in main.go. One difference matters: slices.Max panics on an empty slice, where your version returned false. Check the length first wherever a slice can be empty, such as a filter result or an empty upload.
slices has no function that returns a filtered copy, so Filter stays. The nearest is slices.DeleteFunc, which removes matching elements in place and reuses the slice's memory. Clone first if the caller still needs the original:
rm constraints.go
cat > main.go <<'GO'
package main
import (
"fmt"
"slices"
"strings"
"example.com/generics/set"
)
type Order struct {
ID string
Paid bool
}
func main() {
nums := []int{3, 8, 15, 22, 41}
cities := []string{"Lagos", "", "Nairobi", " ", "Accra"}
orders := []Order{{"A1", true}, {"A2", false}, {"A3", true}}
fmt.Println(Filter(nums, func(n int) bool { return n%2 == 0 }))
fmt.Println(Filter(cities, func(c string) bool { return strings.TrimSpace(c) != "" }))
fmt.Println(Filter(orders, func(o Order) bool { return o.Paid }))
fmt.Println(slices.Index(cities, "Nairobi"), slices.Index(orders, Order{"A2", false}), slices.Index(nums, 99))
fmt.Println(slices.Contains(cities, "Accra"), slices.Max(nums))
evens := slices.DeleteFunc(slices.Clone(nums), func(n int) bool { return n%2 != 0 })
fmt.Println(evens, nums)
prices := []Kobo{150000, 2550, 99}
fmt.Println(Sum(prices), slices.Max(prices))
visited := set.New("Lagos", "Accra", "Lagos", "Kigali")
fmt.Println(visited.Len(), slices.Sorted(visited.All()))
fmt.Println(slices.Sorted(visited.Map(strings.ToUpper).All()))
}
GO
go vet ./...
go run .Look at a signature with go doc slices.Index: it is func Index[S ~[]E, E comparable](s S, v E) int. The S ~[]E parameter accepts any type whose underlying type is a slice, so a named type such as type Cities []string goes in and comes back as Cities, not as a plain []string. Your Filter takes []T and would return a plain slice; the same trick would fix that if you need it.
Check it worked
go test ./set/ still passes with the shorter All. go run . prints 2 1 -1 from slices.Index, true 41, and [8 22] [3 8 15 22 41], which shows that the clone protected nums. constraints.go is gone and go vet ./... is silent.
Step 8 · Decide when code should stay non-generic
Generics earn their place when the same code runs over different element types and the logic does not care which: containers like Set, and helpers over slices, maps and channels like Filter. Most other code is clearer without them. Before you add a type parameter, ask:
- Does the function only call methods on its argument? Then take an interface.
func PrintTotal(w io.Writer, ...)is simpler thanfunc PrintTotal[W io.Writer](w W, ...)and does the same job. - Is there one real type today? Write it for that type. Make it generic when the second type turns up, not before.
- Does each type need different code? A type parameter cannot switch on
Tcleanly; use an interface with methods, or separate functions. - Would
anywith a type assertion inside be needed? Then the generic version is not checking anything for you. - Do the
slices,maps,cmporiterpackages already have it? Use theirs.
Add a report function that follows the first rule. It writes to anything with a Write method, such as the terminal, a file or a strings.Builder in a test:
cd ~/generics-demo
cat > report.go <<'GO'
package main
import (
"fmt"
"io"
)
// PrintTotal writes the number of prices and their sum to w. It only
// needs w's Write method, so a plain interface parameter is enough.
func PrintTotal(w io.Writer, prices []Kobo) {
fmt.Fprintf(w, "%d items, total %v\n", len(prices), Sum(prices))
}
GO
cat > print_total_test.go <<'GO'
package main
import (
"strings"
"testing"
)
func TestPrintTotal(t *testing.T) {
var b strings.Builder
PrintTotal(&b, []Kobo{150000, 2550, 99})
if got, want := b.String(), "3 items, total NGN 1526.49\n"; got != want {
t.Fatalf("PrintTotal wrote %q, want %q", got, want)
}
}
GO
gofmt -l .
go vet ./...
go test ./...The module now has one generic function you wrote (Filter), one generic constraint (Number) with Sum, one generic type (Set) with a generic method, and an ordinary function that uses them without being generic itself. That ratio, a little generic code at the bottom and plain code on top, is typical of well-written Go.
Check it worked
gofmt -l . and go vet ./... print nothing. go test ./... prints ok example.com/generics and ok example.com/generics/set. You can name, for each of Filter, Sum, Set and PrintTotal, why it is or is not generic.
To remove the project when you are done:
cd ~
rm -rf ~/generics-demoNext steps
- Cover
FilterandSetwith table tests and a fuzz target in Test Go code with table tests, fuzzing and benchmarks. - Run the same kind of slice work across goroutines with a worker pool, a deadline and a mutex in Run work concurrently in Go with goroutines and channels.
- Compare Go's constraints with TypeScript's
extendsbounds in Write reusable TypeScript with generics. - If any of the Go basics here were new, start with Hello World in Go.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials