← Fundamentals
Fundamentals

Generics and parametric polymorphism

How do you write one function that works for many types?

Type parameters let one operation keep useful type information across different callers.

Outcome

Write a generic function that uses only what its parameters promise, add the bound or constraint the body needs, return a value that can be absent instead of a misleading default, and keep generic arithmetic in a type that holds the answer.

Terminology (4)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Type parameter
A placeholder, such as T, for a type the caller supplies or the compiler infers.
Bound or constraint
What a type parameter must support: extends in TypeScript, a constraint in Go, a trait bound in Rust, a concept in C++.
Instantiation
A generic definition used with concrete type arguments. Rust monomorphization and C++ template specialization support concrete uses; optimization controls the emitted code.
Parametric polymorphism
One definition parameterized by types, using the operations its contract supports. Constraints and callbacks can make behavior depend on supported operations.

One definition parameterized by types

A generic definition introduces a type parameter such as T. The caller supplies a type, often inferred from its arguments, and the signature preserves relationships: a helper accepting a collection of T can return a T rather than discard the element type.

The body needs support for every operation it performs. A bound or constraint states required capabilities; a callback can instead supply an operation such as reading a comparison key. The type argument also affects defaults, ownership and arithmetic, so generic reuse still has a concrete contract.

Go checks a generic body using the operations allowed by its type-parameter constraint. A type set states which types are admitted; any permits broad reuse but supplies fewer operations than an ordered constraint.

01One function, many types

A type parameter stands for the caller’s type

A typed inventory report library selects a product record by a price callback, reads the first value of a price series and averages recorded quantities. These helpers are intended for callers with different record and numeric types. The supplied callers exercise a small set, so a helper must keep its generic contract as well as produce this report.

The inventory library needs a selection helper before it is connected to the report’s full records. These reduced numeric and string or callback-based calls check how one body selects a value for different caller types. Predict both results.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
	"cmp"
	"fmt"
)

func Largest[T cmp.Ordered](items []T) T {
	best := items[0]
	for _, item := range items[1:] {
		if item > best {
			best = item
		}
	}
	return best
}

func main() {
	fmt.Println(Largest([]int{3, 9, 4}), Largest([]string{"fig", "pear"}))
}
What is printed?
Go · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
go run main.go

Use the setup from the first reading for your language.

02Bounds and constraints

Each operation needs support from the type

A proposed library helper reads an extra property or compares values. Inspect the declared type requirements and the supplied caller before deciding whether that use is accepted.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

func Largest[T any](items []T) T {
	best := items[0]

	for _, item := range items[1:] {
		if item > best {
			best = item
		}
	}

	return best
}

func main() {
	fmt.Println(Largest([]int{3, 9, 4}))
}
What does go build do?

03An empty answer

A default value is not the same as no value

A price-series import can contain no observation, while a real first observation can be zero. These reduced first-value probes show what their return carriers keep or erase; predict the printed results.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

func First[T any](items []T) T {
	var zero T

	if len(items) == 0 {
		return zero
	}

	return items[0]
}

func main() {
	fmt.Printf("%d %d %q\n", First([]int{4, 7}), First([]int{}), First([]string{}))
}
What is printed?

04Repair the typed inventory report

Keep the selected record, distinguish no price, then preserve the average

The first helper must return the original record with the highest quoted price; the callback tells it how to read a price without assuming a particular product shape. The first-value helper feeds a price-series report where an empty series means none and a genuine first price of 0 remains 0. The average helper formats integral quantity observations to two decimal places, including their fractional mean.

These are three library contracts used by the inventory report, with a complete supplied caller for each. Ties keep the earlier record. Empty and zero witnesses protect distinct meanings; fractional cases protect the arithmetic performed before formatting.

Repair the typed inventory report

A comparison in a generic body, an empty generic answer, then arithmetic in the type parameter.

  1. easy · F-GENERIC-V4-1 Find the dearest fruit
  2. medium · F-GENERIC-V4-2 Report each basket
  3. hard · F-GENERIC-V4-3 Average the quantities
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.