From 9152e211328f735e7dadaf69780920d64af09a2a Mon Sep 17 00:00:00 2001 From: Robert Griesemer Date: Fri, 28 Jan 2022 15:34:40 -0800 Subject: [PATCH] spec: add section on comparable constraint For #50646. Fixes #50791. Change-Id: I8fec25ae3f0280c5b5a778011d23842b886ba79e Reviewed-on: https://go-review.googlesource.com/c/go/+/381896 Trust: Robert Griesemer Reviewed-by: Ian Lance Taylor --- doc/go_spec.html | 49 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/doc/go_spec.html b/doc/go_spec.html index c653cbffc0..69ac1d353f 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -1,6 +1,6 @@ @@ -2656,6 +2656,53 @@ may be omitted for convenience: type Constraint ~int // illegal: ~int is not inside a type parameter list + + +

+The predeclared +interface type comparable +denotes the set of all concrete (non-interface) types that are +comparable. Specifically, +a type T implements comparable if: +

+ +
    +
  • + T is not an interface type and T supports the operations + == and !=; or +
  • +
  • + T is an interface type and each type in T's + type set implements comparable. +
  • +
+ +

+Even though interfaces that are not type parameters can be +compared +(possibly causing a run-time panic) they do not implement +comparable. +

+ +
+int                          // implements 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
+interface{ comparable }      // type parameter only: implements comparable
+interface{ ~int | ~[]byte }  // type parameter only: does not implement comparable (not all types in the type set are comparable)
+
+ +

+The comparable interface and interfaces that (directly or indirectly) embed +comparable may only be used as type constraints. They cannot be the types of +values or variables, or components of other, non-interface types. +

+

Variable declarations

-- 2.50.0