The comparable constraint limits generic type parameters to types that support equality comparison operators like == and !=.
The comparable constraint restricts a type parameter to types that support equality comparison using == and !=. Use it in generic function or type definitions to ensure the type can be compared, such as for map keys or sorting.
func Contains[T comparable](slice []T, item T) bool {
for _, v := range slice {
if v == item {
return true
}
}
return false
}
The comparable constraint is a rule for generic code that says, "This function only works with types you can check for equality." It allows you to write flexible code that handles numbers, strings, or custom structs, but it will reject types like slices or maps that cannot be compared directly. Think of it as a safety check ensuring the data you pass in can be tested for matches.