liveBook · Manning

Comparable

As explained in Learn Go with Pocket-Sized Projects

comparable is Go's predeclared generic constraint satisfied by types whose values can be compared with == or !=.

comparable is Go’s built-in generic constraint for types whose values support equality with == or !=. It enables generic map keys and cache keys. section 7.1.1 section 7.1.3

Comparable types include:

A comparable cache key

A generic cache can restrict its key type while leaving values unrestricted: type Cache[K comparable, V any] struct { data map[K]V }. Integer keys and string values provide a simple use case; other comparable key types can also be substituted. section 7.1.3

Listing 7.1 cache.go
// Cache is key-value storage.
type Cache[K comparable, V any] struct {
    data  map[K]V
}

Inspect the cache declaration to see comparable applied directly to the key type parameter. section 7.1.3

Listing 7.2 cache.go
// New creates a usable Cache.
func New[K comparable, V any]() Cache[K, V] {
    return Cache[K, V]{
        data: make(map[K]V),
    }
}

Inspect the constructor to see the same constraint carried through generic cache creation. section 7.1.3

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines equality support, enumerates comparable and non-comparable types, and applies the constraint in a generic cache.
Examples
Uses integer cache keys, string values, and a map[K]V declaration.
What it assumes
Introduces comparable alongside generic type parameters and the any constraint.
What you can do after
Build it from scratch by declaring generic map-backed types with equality-valid key parameters.
How it connects
Connects generics, type constraints, maps, equality comparison, and caching.

Also explained in

Compare how 3 books explain comparable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.