Use any and comparable constraints
Use any and comparable constraints
any aliases interface{} and admits all types as type arguments. It does not permit arbitrary arithmetic or equality on T. comparable permits equality operations and map keys in generic code. Select the weakest constraint that supports the operations your function needs.
package main
import ( "fmt")
func singleton[T any](v T) []T { return []T{v} }func main() { fmt.Println(singleton(8), singleton("tea"))}Creating a slice and storing T values needs no equality or arithmetic, so any is sufficient. A generic function is not allowed to use an operation just because one particular caller happens to pass a type supporting it.
Expected output:
[8] [tea]Use equality to find a value
package main
import ( "fmt")
func contains[T comparable](xs []T, want T) bool { for _, x := range xs { if x == want { return true } } return false}func main() { fmt.Println(contains([]int{1, 2}, 2), contains([]string{"a"}, "b"))}Equality is permitted by comparable. A slice itself cannot be used as T here because slices cannot be compared to one another. Interface type arguments have a special satisfaction rule discussed in lesson 5.
Expected output:
true falseTry it locally
Write same[T comparable](a,b T) bool and print comparisons of 3 with 3 and "a" with "b".
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generics 03: Use any and comparable constraints
Check the lesson objective before moving on.
Can a function with T any compare two T values using ==?
Which constraint directly permits map keys of type T?