Generics

suggest change

Introduced in Go 1.18, Generics (parameterized types) allow you to write functions, data structures, and interfaces that work with any set of types while preserving compile-time type safety. Before generics, writing reusable code required either duplicate implementations per type, empty interfaces (any / interface{}) with runtime type assertions, or code generation.


1. Generic Functions

A generic function declares one or more type parameters enclosed in square brackets [...] after the function name:

package main

import "fmt"

// Map applies a transform function to every element of a slice and returns a new slice
func Map[T any, R any](items []T, transform func(T) R) []R {
	result := make([]R, len(items))
	for i, item := range items {
		result[i] = transform(item)
	}
	return result
}

func main() {
	numbers := []int{1, 2, 3, 4, 5}

	// Go automatically infers type arguments T=int, R=string:
	strings := Map(numbers, func(n int) string {
		return fmt.Sprintf("Number: %d", n*10)
	})

	fmt.Println(strings)
	// Output: [Number: 10 Number: 20 Number: 30 Number: 40 Number: 50]
}

Type Argument Inference

You can explicitly pass type arguments: Map[int, string](numbers, ...). However, in most cases, Go's compiler automatically infers the types from function arguments.


2. Built-in Constraints: any and comparable

Type constraints restrict which types can be passed as type arguments.

any

any is a predeclared identifier and alias for interface{}. It permits any type:

func PrintSlice[T any](items []T) {
	for _, item := range items {
		fmt.Printf("%v ", item)
	}
	fmt.Println()
}

comparable

The built-in comparable constraint permits any type that supports equality comparisons using == and != (booleans, numbers, strings, pointers, channels, interfaces, arrays of comparable types, and structs whose fields are comparable). It is required when using a type parameter as a map key:

package main

import "fmt"

// Contains returns true if target exists within the slice
func Contains[T comparable](slice []T, target T) bool {
	for _, v := range slice {
		if v == target {
			return true
		}
	}
	return false
}

// Keys returns all keys from a map
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
}

func main() {
	fruits := []string{"apple", "banana", "cherry"}
	fmt.Println(Contains(fruits, "banana")) // true
	fmt.Println(Contains(fruits, "orange")) // false

	scores := map[string]int{"Alice": 95, "Bob": 80}
	fmt.Println(Keys(scores)) // [Alice Bob] (map order varies)
}

3. Custom Constraints and the Tilde ~ Operator

To permit comparison operators like <, <=, >, >=, define a constraint using type sets:

package main

import "fmt"

// Number permits any integer or floating-point type
type Number interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float32 | ~float64
}

// Min returns the smaller of two numbers
func Min[T Number](a, b T) T {
	if a < b {
		return a
	}
	return b
}

The Tilde ~ Approximation Operator

The ~ operator (e.g. ~int) means "any type whose underlying type is int". Without ~, a custom defined type like type Celsius float64 would not satisfy the constraint:

type Celsius float64

var boiling Celsius = 100.0
var freezing Celsius = 0.0

// Compiles because Number uses ~float64:
lowest := Min(boiling, freezing)
fmt.Println("Lowest temperature:", lowest) // 0

Tip: In Go 1.21+, the standard library package cmp provides the cmp.Ordered constraint for all types supporting <, <=, >, >=.


4. Generic Types and Data Structures

You can parameterize structs and custom types to build reusable data structures:

package main

import (
	"errors"
	"fmt"
)

// Stack is a thread-unsafe Last-In-First-Out (LIFO) stack
type Stack[T any] struct {
	elements []T
}

func (s *Stack[T]) Push(item T) {
	s.elements = append(s.elements, item)
}

func (s *Stack[T]) Pop() (T, error) {
	var zero T
	if len(s.elements) == 0 {
		return zero, errors.New("stack is empty")
	}
	lastIdx := len(s.elements) - 1
	item := s.elements[lastIdx]
	s.elements = s.elements[:lastIdx]
	return item, nil
}

func (s *Stack[T]) Len() int {
	return len(s.elements)
}

func main() {
	// Stack of strings
	stringStack := Stack[string]{}
	stringStack.Push("first")
	stringStack.Push("second")

	val, _ := stringStack.Pop()
	fmt.Println("Popped:", val) // Output: second

	// Stack of integers
	intStack := Stack[int]{}
	intStack.Push(42)
	intStack.Push(100)

	intVal, _ := intStack.Pop()
	fmt.Println("Popped:", intVal) // Output: 100
}

5. When to Use Generics (and When Not To)

When to Use Generics

  1. Container Data Structures: Stacks, queues, linked lists, binary trees, ring buffers, and caches.
  2. General-purpose Collection Algorithms: Transforming, filtering, deduplicating, or sorting slices and maps (e.g., standard library slices and maps packages in Go 1.21+).
  3. Common Utility Functions: Min, Max, Clamp, or channel pipelines operating across numerical types.

When NOT to Use Generics

  1. When Interfaces Already Solve the Problem: If different types just need to implement a set of methods (e.g., io.Reader, fmt.Stringer), prefer standard interfaces.
  2. Do Not Overcomplicate Public APIs: If a function only ever operates on []byte or string, do not make it generic.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents