The comparable interface
August 7, 2023
Are you as curious about Fuzzing in Go as I am? On today’s live stream, I’ll be live coding my way through John Arundel’s 4-part series on Go Fuzzing. I hope you’ll join me!
Today we’re learning about the predeclared comparable
interface. But before this discussion makes sense, we should jump ahead to one key definition. That of the concept of “strictly comparable”:
A type is strictly comparable if it is comparable and not an interface type nor composed of interface types.
With this in mind, the rest of the discussion on the comparable
interface should make more sense…
Type constraints
…
The predeclared interface type
comparable
denotes the set of all non-interface types that are strictly comparable.Even though interfaces that are not type parameters are comparable, they are not strictly comparable and therefore they do not implement
comparable
. However, they satisfy comparable.int // implements comparable (int is strictly comparable) []byte // does not implement comparable (slices cannot be compared) interface{} // does not implement comparable (see above) interface{ ~int | ~string } // type parameter only: implements comparable (int, string types are stricly comparable) interface{ comparable } // type parameter only: implements comparable (comparable implements itself) interface{ ~int | ~[]byte } // type parameter only: does not implement comparable (slices are not comparable) interface{ ~struct{ any } } // type parameter only: does not implement comparable (field any is not strictly comparable)
The
comparable
interface and interfaces that (directly or indirectly) embedcomparable
may only be used as type constraints. They cannot be the types of values or variables, or components of other, non-interface types.
So what are the key points to pull out of this?
- The
comparable
interface is pre-defined, and is implemented by types that are strictly comparable. - The
comparable
interface can only be used as a type constraint. You cannot create a variable of typecomparable
.
Tomorrow we’ll see how type constraints are satisfied, which will shed a bit more light on this topic.
Quotes from The Go Programming Language Specification Version of December 15, 2022