Type parameters and constraints
A type parameter is a type written in square brackets after the function name, and a constraint is the set of types it accepts. The compiler checks the body once against the constraint, not once per type, so the body may use only operations the constraint promises. That is the whole design: generics remove the copy of a function per type without becoming templates. The interfaces lesson introduced interface constraints as method sets; this one adds unions of types.
A generic function
[T int | float64] declares T and allows exactly those two types. The body adds values of T, which is licensed because both types support +. The call site writes no type argument: the compiler infers T from the slice, which the next lesson takes further.
package main
import "fmt"
func Sum[T int | float64](xs []T) T {
var total T
for _, x := range xs {
total += x
}
return total
}
func main() {
fmt.Println(Sum([]int{1, 2, 3}))
fmt.Println(Sum([]float64{1.5, 2.5}))
}
go run sum.go
6
4
The two calls ran the same instantiated code for int and float64. A type parameter is not an interface value at run time: the compiler generates a version per concrete type, or a dictionary-based one, and the call does not box the elements. That is why a generic function is fast and an any based one usually is not.
A named constraint and the tilde
A constraint can be a named interface, which keeps the signature readable. The tilde matters: ~float64 admits float64 and every named type whose underlying type is float64, such as Celsius. Without it, a named type would not satisfy the constraint even though its values are the same shape, which is the opposite of what callers expect.
package main
import "fmt"
type Number interface {
~int | ~int64 | ~float64
}
type Celsius float64
func Max[T Number](xs []T) T {
best := xs[0]
for _, x := range xs[1:] {
if x > best {
best = x
}
}
return best
}
func main() {
fmt.Println(Max([]int{3, 9, 4}))
fmt.Println(Max([]int64{3, 9, 4}))
fmt.Println(Max([]Celsius{3, 9, 4}))
}
go run max.go
9
9
9
All three calls compiled because int, int64 and Celsius are covered by the tilde terms. Use a tilde for every term in a constraint that is meant to accept domain types, and leave it out only when the constraint is deliberately restricted to the built-in type.
comparable
comparable is the predeclared constraint for types that support ==, and it is what a generic lookup needs. It is the one constraint that is satisfied by every comparable type, including structs and arrays of comparable fields, which is why the standard library uses it for map keys and index functions.
package main
import "fmt"
func Index[T comparable](xs []T, want T) int {
for i, x := range xs {
if x == want {
return i
}
}
return -1
}
func main() {
fmt.Println(Index([]string{"go", "rust", "c"}, "rust"))
fmt.Println(Index([]int{4, 8, 15}, 16))
}
go run index.go
1
-1
Both calls compiled because strings and ints are comparable. A map, a slice or a function is not, and Index([]map[string]int{m}, m) is refused at the call site with a message that names the type argument and the constraint.
A constraint the body outgrows
The body of a generic function is checked against the constraint, so an operation the constraint does not promise is a compile error at the definition, not a surprise per call. Here any promises nothing, not even addition, so v + v has no meaning for an arbitrary T. The fix is a constraint with the operation, such as the union from the previous section.
package main
import "fmt"
func double[T any](v T) T {
return v + v
}
func main() {
fmt.Println(double(2))
}
go build -o badbody badbody.go
# command-line-arguments
./badbody.go:6:9: invalid operation: operator + not defined on v (variable of type T constrained by any)
The message names the operator, the variable and the constraint, which is more precise than most generic errors. If a constraint needs many operations, the usual answer is an interface with the methods and a generic function that calls them, not a longer union: a union of every numeric type cannot express methods that only some of them have.
Exercises
- Write Filter[T any](xs []T, keep func(T) bool) []T and use it on ints and strings. Why does it need no constraint at all?
- Add a Min to the Number constraint and call both Max and Min on a slice of Celsius. Which part of the constraint made that compile?
- Try Index([]map[string]int{m}, m). Copy the compiler message and explain which word in the constraint refused the call.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a type parameter constraint promise the function body?
Answer
The operations the body may use on values of that type
The body is checked once against the constraint, so only promised operations are allowed.
-
What does this program print?
package main import "fmt" func Sum[T int | float64](xs []T) T { var total T for _, x := range xs { total += x } return total } func main() { fmt.Println(Sum([]int{1, 2, 3})) fmt.Println(Sum([]float64{1.5, 2.5})) }Answer
6 / 4
The ints add to 6 and the floats 1.5 and 2.5 add to 4, printed without a decimal for the float sum.
-
What does the tilde in ~float64 add to a constraint?
Answer
It also admits named types whose underlying type is float64
With the tilde, a type like Celsius satisfies a numeric constraint.
-
What does this program print?
package main import "fmt" type Number interface { ~int | ~int64 | ~float64 } type Celsius float64 func Max[T Number](xs []T) T { best := xs[0] for _, x := range xs[1:] { if x > best { best = x } } return best } func main() { fmt.Println(Max([]int{3, 9, 4})) fmt.Println(Max([]int64{3, 9, 4})) fmt.Println(Max([]Celsius{3, 9, 4})) }Answer
9 / 9 / 9
Max returns the element with the largest value, and Celsius is a plain float64 for printing here.
-
Which types does comparable admit?
Answer
Every type that supports ==
Maps, slices and functions are excluded, because == is not defined on them.
-
What does the second line of this program print?
package main import "fmt" func Index[T comparable](xs []T, want T) int { for i, x := range xs { if x == want { return i } } return -1 } func main() { fmt.Println(Index([]string{"go", "rust", "c"}, "rust")) fmt.Println(Index([]int{4, 8, 15}, 16)) }Answer
1 / -1
16 is not in the slice, so Index returns -1.
-
What does the compiler say about this program?
package main import "fmt" func double[T any](v T) T { return v + v } func main() { fmt.Println(double(2)) }Answer
invalid operation: operator + not defined on v (variable of type T constrained by any)
any does not promise addition, so the body cannot be typed; the fix is a union constraint.
-
How is a generic function instantiated at the call site?
Answer
The compiler infers the type arguments from the arguments, or they are written in brackets
Inference is the normal route; an explicit type argument is the escape hatch.
-
Why is a generic function usually faster than one taking any?
Answer
The compiler knows the concrete type and does not box the values
An any argument boxes the value; a type parameter keeps it in its own representation.
-
A constraint needs three methods of a type. What is the better tool?
Answer
An interface constraint with those methods
Method sets are what interfaces express; a union cannot name methods.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev