liveBook · Manning

Comparable

As explained in 100 Go Mistakes and How to Avoid Them

Comparable is a Go predeclared constraint satisfied by types whose values can be compared with == or !=.

A value that looks equal to another is not necessarily comparable with `==`. Adding a slice field to a struct makes `cust1 == cust2` fail to compile, even when both slices contain the same values. Slices and maps cannot be compared with `==` or `!=`; a struct can be compared only when its fields can be compared. section 3.13

This distinction matters for generic map keys. `any` permits types that cannot be map keys, such as slices. The predeclared `comparable` constraint restricts a key type parameter to types whose values support `==` and `!=`, while leaving the value type unrestricted. section 2.9.1

func getKeys[K comparable, V any](m map[K]V) []K {   #1
    var keys []K                                     #2
    for k := range m {
        keys = append(keys, k)
    }
    return keys
}

The key-extraction function uses `K comparable` for map keys and `V any` for values; its result retains the key type as `[]K`. section 2.9.1

An `any` variable introduces a different trap. Comparing two `any` values holding integers prints `true`, but comparing two that hold structs with slice fields compiles and then panics at run time. For values containing slices, use `reflect.DeepEqual` or define an equality method that compares the relevant fields and slice elements. section 3.13

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains the constraint through a generic function and traces compile-time errors versus a runtime comparison panic.
Examples
Uses generic key extraction, a struct changed to include a slice, and comparisons of values held in `any` variables.
What it assumes
Assumes familiarity with Go maps and structs while introducing generic constraints through a key-extraction function.
What you can do after
Diagnose/debug with it when a map key or equality expression fails to compile, or an interface comparison panics.
How it connects
Connects generic constraints and map keys with equality operators, interface values, structs, slices, and `reflect.DeepEqual`.

Also explained in

Compare how 3 books explain comparable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.