Reason about constraint satisfaction and comparability
Reason about constraint satisfaction and comparability
Constraint satisfaction is checked at compile time. Since Go 1.20, a comparable interface type such as any can satisfy comparable even though its dynamic values may be noncomparable. Comparing two interface values whose matching dynamic type is a slice, map or function can panic. Do not equate satisfaction with a guarantee against runtime panics.
package main
import ( "fmt")
func equal[T comparable](a, b T) bool { return a == b }func main() { fmt.Println(equal[any](3, 3), equal[any](3, "3"))}Both instantiations with any compile on Go 1.20+. Interface values with different dynamic types compare unequal. The same dynamic type must support equality for comparison to succeed. equal[any]([]int{1}, []int{1}) would panic; it is deliberately not executed here.
Expected output:
true falseRestrict the allowed types
package main
import ( "fmt")
func keyEqual[T ~int | ~string](a, b T) bool { return a == b }
type ID int
func main() { fmt.Println(keyEqual(ID(3), ID(4)), keyEqual("x", "x"))}This narrower set excludes interface type arguments and permits only types with underlying int or string. If you need broader comparability, document the dynamic-value limitation, rather than pretending comparable alone removes it.
Expected output:
false trueTry it locally
Define KeyEqual with constraint ~string and test a defined type Key string with equal and unequal values.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generics 05: Reason about constraint satisfaction and comparability
Check the lesson objective before moving on.
Can any satisfy comparable in Go 1.20+?
Which constraint excludes interface type arguments here?