ProgramGuru

The comparable Constraint

Start with The comparable Constraint

The comparable constraint represents types that can be compared with == and != and can be used as Go map keys.

What you’ll learn

  • Explain the main purpose of the comparable constraint.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Arrays and structs may be comparable when their elements and fields are comparable. Slices and maps are not comparable to one another, so they cannot be ordinary map keys. There are subtle differences between the comparability accepted by a generic constraint and whether equality may panic for a particular dynamic interface value.

Use comparable for set-like collections or equality-based lookup. It does not provide <, > or an ordering relation.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for comparableComparable keys let a map track equality efficiently.Input sliceStep 1Map[T] seenStep 2Keep unseen valuesStep 3Ordered unique sliceStep 4Comparable keys let a map track equality efficiently.
Comparable keys let a map track equality efficiently.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func unique[T comparable](values []T) []T {
	seen := make(map[T]bool)
	result := make([]T, 0, len(values))
	for _, v := range values {
		if !seen[v] {
			seen[v] = true
			result = append(result, v)
		}
	}
	return result
}
func main() {
	fmt.Println(unique([]int{2, 2, 4, 2, 5}))
	fmt.Println(unique([]string{"a", "b", "a"}))
}

Output

[2 4 5]
[a b]

Trace what the program does

The function uses each element as a map key to recognize previously seen values. It keeps first occurrences in their original order and returns [2 4 5] and [a b].

Avoid common mistakes

  • Slices cannot be used directly as map keys.
  • comparable provides equality, not sorted order.

Try it yourself

Use unique with a struct containing two integers, then try to explain why it would reject a struct containing a slice.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which operation is supported by comparable constraints?
Choose one answer. You can try again.

Answer and explanation

Using T as a map key

Correct. The function uses each element as a map key to recognize previously seen values.

What you should remember

You have practiced The comparable Constraint in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Generic Methods →