apply from the last lesson only works on []int. To transform a slice of strings you would need a second copy with string in place of int, and a third for records. The logic would be identical; only the types would change. Type parameters remove that duplication. A generic function lists its type parameters in square brackets before the ordinary parameters, and the body uses those names wherever a concrete type would go.
func Map[T, R any](values []T, f func(T) R) []R reads: for any types T and R, take a slice of T and a function from T to R, and return a slice of R. any is the constraint. It says which types are allowed, and any allows every type.
Predict and run
Go works out T and R from the arguments. What does each line print?
package main
import (
"fmt"
"strings"
)
func Map[T, R any](values []T, f func(T) R) []R {
result := make([]R, len(values))
for i, v := range values {
result[i] = f(v)
}
return result
}
func main() {
items := []string{"tent", "drill", "lamp"}
fmt.Println(Map(items, strings.ToUpper))
fmt.Println(Map(items, func(s string) int { return len(s) }))
}Check your prediction
[TENT DRILL LAMP]
[4 5 4]In the first call, strings.ToUpper has type func(string) string, so R is string. In the second, the literal returns an int, so R is int and the result is a []int. Try Map[string, int](items, ...) with the types written out. It means the same thing; explicit type arguments are only needed when Go cannot infer them.
Constraints say what the body may do
Inside a generic function you can only use operations that every allowed type supports. With any, that is very little: you can assign, pass and return values, but you cannot compare them with <, because some types have no order. To use <, constrain the type parameter to types that are ordered. The standard library's cmp.Ordered covers the integers, floats and strings.
package main
import (
"cmp"
"fmt"
)
func largest[T cmp.Ordered](values []T) (T, bool) {
var best T
if len(values) == 0 {
return best, false
}
best = values[0]
for _, v := range values[1:] {
if v > best {
best = v
}
}
return best, true
}
func main() {
fmt.Println(largest([]int{12, 40, 7}))
fmt.Println(largest([]string{"tent", "drill", "lamp"}))
fmt.Println(largest([]float64{}))
}40 true
tent true
0 falseStrings compare letter by letter, so tent is the largest of the three names. var best T declares a variable of the type parameter. It holds that type's zero value: 0 for numbers and "" for strings. Returning it with false is the usual way to say "there was no answer" without inventing a sentinel value that might also be a real one.
When generics help
Reach for a type parameter when you have written, or are about to write, the same function for several types, and the body does not care which type it is. Collections and algorithms over them, such as Map, largest or a set, are the classic cases. If the body would need a type switch to behave differently per type, an interface or separate functions usually read better.
Generic code is still checked at compile time
largest([]bool{true}) does not compile: bool does not satisfy cmp.Ordered. The mistake is caught where the function is called, not when the program runs. That is the difference from accepting any and checking types yourself at run time.
Practice
Your turn
Write Filter[T any](values []T, keep func(T) bool) []T, which returns the values for which keep is true, in their original order. Use it to keep the even numbers from 1 to 6, and the item names longer than four letters from tent, drill and lantern.
The output should be:
[2 4 6]
[drill lantern]package main
func main() {
// Write Filter, then call it with two element types.
}Hint 1: the idea
The function body never looks inside a T. It only passes each value to keep and appends the ones it accepts.
Hint 2: a first step
Start the result with var result []T and append each kept value.
Worked solution
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() {
numbers := []int{1, 2, 3, 4, 5, 6}
fmt.Println(Filter(numbers, func(n int) bool { return n%2 == 0 }))
items := []string{"tent", "drill", "lantern"}
fmt.Println(Filter(items, func(s string) bool { return len(s) > 4 }))
}[2 4 6]
[drill lantern]T is int in the first call and string in the second, and both calls share one implementation. tent has exactly four letters, so it checks that the rule is "longer than", not "at least".
Completion is saved in this browser only. It does not measure mastery.