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:
- Booleans, numbers, strings, pointers, and channels. section 7.1.1
- Arrays whose element types are comparable. section 7.1.1
- Structs whose fields are all comparable. section 7.1.1
- Slices, maps, and functions are not comparable. section 7.1.1
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
Inspect the constructor to see the same constraint carried through generic cache creation. section 7.1.3


