Understand the contract
A generic function declares type parameters alongside ordinary parameters. Constraints describe which types are allowed and which operations the function can perform. Use generics when one algorithm genuinely applies to several types without depending on a particular representation or behavior beyond the constraint.
The contains function uses T comparable because it compares elements with ==. A constraint of any would allow more types but would not permit that comparison. Slices and maps are not comparable and cannot be used as element types for this function under that constraint.
Work through the example
Go infers T as int in the first call and string in the second. The function returns as soon as it finds a match and returns false for an empty input. Its behavior is the same for both types, which is the repetition a type parameter removes.
package main
import "fmt"
func contains[T comparable](values []T, target T) bool {
for _, value := range values {
if value == target { return true }
}
return false
}
func main() {
fmt.Println(contains([]int{1, 2, 3}, 2))
fmt.Println(contains([]string{"go"}, "api"))
}Watch this boundary
Generics do not make every abstraction simpler. An interface fits consumers that need methods, and a concrete function often gives the clearest API for one data type. Avoid adding type parameters that appear only once and do not express a useful relationship between inputs and results.
Practice with a changed input
Test contains with an empty slice, duplicates and a missing value. Try a slice-of-slices input and read the compiler error before deciding whether a custom equality function would fit that use case.
Lesson 31 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services