Writing one function for many types

Say you write a function that returns the last item of a []int. Later you need the same thing for a []string, and then for a []float64. The code would be the same every time, only the type changes. Generics let you write the function once and leave the type open. Go fills it in each time you call the function.

package main

import "fmt"

func Last[T any](values []T) T {
	return values[len(values)-1]
}

func main() {
	fmt.Println(Last([]int{3, 9, 4}))
	fmt.Println(Last([]string{"pear", "fig"}))
}

Output:

4
fig

[T any] comes right after the function name. It declares a type parameter called T. A type parameter is a name that stands for a type, the way a normal parameter stands for a value. T can be any type. values []T is a slice of T values, and the function returns one T.

In the first call, Go sees a []int and uses int for T. In the second call, T is string. Go works out T from the arguments, so you rarely write it yourself. You can, though: Last[int]([]int{3, 9, 4}) gives the same result.

Constraints

any allows every type, so inside the function Go only lets you do what works for every type. Comparing with > is not one of those things:

package main

import "fmt"

func Bigger[T any](a, b T) T {
	if a > b {
		return a
	}
	return b
}

func main() {
	fmt.Println(Bigger(3, 7))
}

Output:

# command-line-arguments
./main.go:6:5: invalid operation: a > b (type parameter T is not comparable with >)

Some types, like bool or a struct, have no order, so Go refuses. To fix this, replace any with a constraint: a rule that says which types T may be. The simplest constraint lists the types with | between them:

package main

import "fmt"

func Sum[T int | float64](values []T) T {
	var total T
	for _, v := range values {
		total += v
	}
	return total
}

func main() {
	fmt.Println(Sum([]int{1, 2, 3}))
	fmt.Println(Sum([]float64{1.5, 2}))
}

Output:

6
3.5

Every type in the list supports +, so total += v is allowed. var total T starts the total at the zero value of T, which is 0 for both.

For > and <, Go has a ready-made constraint called cmp.Ordered in the cmp package. It lists every integer and float type, and string:

package main

import (
	"cmp"
	"fmt"
)

func Bigger[T cmp.Ordered](a, b T) T {
	if a > b {
		return a
	}
	return b
}

func main() {
	fmt.Println(Bigger(3, 7))
	fmt.Println(Bigger("pear", "fig"))
	fmt.Println(Bigger(2.5, 1.5))
}

Output:

7
pear
2.5

Functions as arguments

Generics work well with the function values from the Function Values lesson. Filter keeps the items for which keep returns true, whatever their type:

package main

import "fmt"

func Filter[T any](values []T, keep func(T) bool) []T {
	var result []T
	for _, v := range values {
		if keep(v) {
			result = append(result, v)
		}
	}
	return result
}

func main() {
	nums := []int{1, 2, 3, 4, 5, 6}
	even := Filter(nums, func(n int) bool {
		return n%2 == 0
	})
	fmt.Println(even)

	words := []string{"go", "rust", "c"}
	long := Filter(words, func(w string) bool {
		return len(w) > 1
	})
	fmt.Println(long)
}

Output:

[2 4 6]
[go rust]

A function can also have more than one type parameter. Map calls f on each item of a []T and collects the results in a []U. Here T is string and U is int:

package main

import "fmt"

func Map[T, U any](values []T, f func(T) U) []U {
	var result []U
	for _, v := range values {
		result = append(result, f(v))
	}
	return result
}

func main() {
	words := []string{"go", "rust", "c"}
	lengths := Map(words, func(w string) int {
		return len(w)
	})
	fmt.Println(lengths)
}

Output:

[2 4 1]

You have used generic functions before. slices.Sort and slices.Contains from The slices Package lesson are written this way, which is why the same function worked for a slice of ints and a slice of strings.

In the exercise, finish the generic function Largest with the cmp.Ordered constraint, so it finds the largest number and the largest word.