Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Built-in Types

The Go comparable constraint

Reference for the predeclared comparable constraint: which types satisfy it, strict versus run-time comparability, use in generic maps and Index functions.

comparable is a predeclared constraint for type parameters. A type argument satisfies it if values of that type can be compared with == and !=. It is what makes generic code such as "find this element" or "use this as a map key" possible.

It can only be used as a type constraint, never as the type of an ordinary variable. For ordering (<, >) use cmp.Ordered instead.

Go
func Index[T comparable](s []T, target T) int {
	for i, v := range s {
		if v == target {
			return i
		}
	}
	return -1
}

Try it

Go A generic Index and a generic set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Interfaces satisfy comparable, but may panic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func F[T comparable](x, y T) bool { return x == y }

type Pair[K comparable, V any] struct {
	Key K
	Val V
}
Type Satisfies comparable?
Booleans, numbers, strings, pointers, channels Yes.
Arrays, structs Yes, if every element or field type does.
Interface types (including any) Yes since Go 1.20, but comparing may panic at run time.
Slices, maps, functions No.

Errors: instantiating F[[]int] is a compile error ("[]int does not satisfy comparable").

Usage notes

  • Strictly versus spec comparable. Interface types are comparable by the language spec, but not "strictly comparable" because the dynamic value may not be. Before Go 1.20, interfaces were rejected as arguments; since then they are accepted, shifting the failure to a run-time panic.
  • Map keys need comparable, so generic map wrappers must constrain the key type exactly like this.
  • Embedding. You can embed comparable in your own constraint interface: interface{ comparable; String() string }.
  • Only equality. It gives you == and !=, nothing else. Use cmp.Ordered for <, or accept a comparison function (as slices.SortFunc does).
  • Floating-point caveat. NaN != NaN, so generic code that relies on reflexive equality can misbehave for floats.
  • The standard library uses it in slices.Index, slices.Contains, slices.Compact, maps.Equal (keys) and sync helpers.