← Project templates

BASICS · IN THE APP NOW

Generic collections

A handful of generic helpers and a generic set type, small enough to read in one sitting and covered by tests.

Offline: standard library only

Open it in the browser Playground →

What it is

Map, Filter and Reduce take type parameters with the any constraint. Max needs the > operator, so it is constrained by cmp.Ordered from the standard library. Set[T comparable] is a generic type whose methods use the type parameter of their receiver.

main applies the helpers to a slice of words; collections_test.go checks each one, including Max with no arguments, which returns the zero value.

Every template's Go program was compiled for GOOS=wasip1 GOARCH=wasm with Go 1.27, then run, vetted and tested before it was added to the app.

Files

text
generics/
├── collections.go
├── collections_test.go
├── go.mod
└── main.go

The code

collections.go

go
package main

import "cmp"

// Map applies f to every element, keeping the order.
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
}

// Filter keeps the elements keep says yes to.
func Filter[T any](items []T, keep func(T) bool) []T {
	var out []T
	for _, item := range items {
		if keep(item) {
			out = append(out, item)
		}
	}
	return out
}

// Reduce folds the slice into one value, starting from initial.
func Reduce[T, A any](items []T, initial A, f func(A, T) A) A {
	acc := initial
	for _, item := range items {
		acc = f(acc, item)
	}
	return acc
}

// Max returns the largest value, or the zero value for no values.
func Max[T cmp.Ordered](values ...T) T {
	var best T
	for i, value := range values {
		if i == 0 || value > best {
			best = value
		}
	}
	return best
}

// Set is a set of comparable values.
type Set[T comparable] struct{ items map[T]struct{} }

func NewSet[T comparable](values ...T) Set[T] {
	set := Set[T]{items: make(map[T]struct{}, len(values))}
	for _, value := range values {
		set.Add(value)
	}
	return set
}

func (s Set[T]) Add(value T)      { s.items[value] = struct{}{} }
func (s Set[T]) Has(value T) bool { _, ok := s.items[value]; return ok }
func (s Set[T]) Len() int         { return len(s.items) }

main.go

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	words := []string{"go", "is", "a", "small", "language", "go"}

	lengths := Map(words, func(w string) int { return len(w) })
	long := Filter(words, func(w string) bool { return len(w) > 2 })
	total := Reduce(lengths, 0, func(sum, n int) int { return sum + n })
	unique := NewSet(words...)

	fmt.Println("lengths:", lengths)
	fmt.Println("long words:", strings.Join(long, " "))
	fmt.Println("letters:", total)
	fmt.Println("distinct words:", unique.Len(), "contains go:", unique.Has("go"))
	fmt.Println("max length:", Max(lengths...))
}

What you learn

  • Declare functions with one or more type parameters, such as Map[T, U any].
  • Constrain a type parameter with cmp.Ordered when the code compares values.
  • Define a generic type, Set[T comparable], backed by map[T]struct{}.
  • Rely on type inference, and spell out the type argument when there is nothing to infer from, as in Max[string]().
  • Check generic code with ordinary tests and slices.Equal.

Run it on a server

Generic code needs Go 1.18 or newer; cmp.Ordered needs Go 1.21 or newer.

bash
go test ./...
go run .

Related: Generics unit of the Go course · Most code that could be generic should not be