|
1 | 1 | <!--{
|
2 | 2 | "Title": "The Go Programming Language Specification - Go 1.18 Draft (incomplete)",
|
3 |
| - "Subtitle": "Version of Jan 28, 2022", |
| 3 | + "Subtitle": "Version of Jan 31, 2022", |
4 | 4 | "Path": "/ref/spec"
|
5 | 5 | }-->
|
6 | 6 |
|
@@ -2656,6 +2656,53 @@ <h4 id="Type_constraints">Type constraints</h4>
|
2656 | 2656 | type Constraint ~int // illegal: ~int is not inside a type parameter list
|
2657 | 2657 | </pre>
|
2658 | 2658 |
|
| 2659 | +<!-- |
| 2660 | +We should be able to simplify the rules for comparable or delegate some of them |
| 2661 | +elsewhere once we have a section that clearly defines how interfaces implement |
| 2662 | +other interfaces based on their type sets. But this should get us going for now. |
| 2663 | +--> |
| 2664 | + |
| 2665 | +<p> |
| 2666 | +The <a href="#Predeclared_identifiers">predeclared</a> |
| 2667 | +<a href="#Interface_types">interface type</a> <code>comparable</code> |
| 2668 | +denotes the set of all concrete (non-interface) types that are |
| 2669 | +<a href="#Comparison_operators">comparable</a>. Specifically, |
| 2670 | +a type <code>T</code> implements <code>comparable</code> if: |
| 2671 | +</p> |
| 2672 | + |
| 2673 | +<ul> |
| 2674 | +<li> |
| 2675 | + <code>T</code> is not an interface type and <code>T</code> supports the operations |
| 2676 | + <code>==</code> and <code>!=</code>; or |
| 2677 | +</li> |
| 2678 | +<li> |
| 2679 | + <code>T</code> is an interface type and each type in <code>T</code>'s |
| 2680 | + <a href="#Interface_types">type set</a> implements <code>comparable</code>. |
| 2681 | +</li> |
| 2682 | +</ul> |
| 2683 | + |
| 2684 | +<p> |
| 2685 | +Even though interfaces that are not type parameters can be |
| 2686 | +<a href="#Comparison_operators">compared</a> |
| 2687 | +(possibly causing a run-time panic) they do not implement |
| 2688 | +<code>comparable</code>. |
| 2689 | +</p> |
| 2690 | + |
| 2691 | +<pre> |
| 2692 | +int // implements comparable |
| 2693 | +[]byte // does not implement comparable (slices cannot be compared) |
| 2694 | +interface{} // does not implement comparable (see above) |
| 2695 | +interface{ ~int | ~string } // type parameter only: implements comparable |
| 2696 | +interface{ comparable } // type parameter only: implements comparable |
| 2697 | +interface{ ~int | ~[]byte } // type parameter only: does not implement comparable (not all types in the type set are comparable) |
| 2698 | +</pre> |
| 2699 | + |
| 2700 | +<p> |
| 2701 | +The <code>comparable</code> interface and interfaces that (directly or indirectly) embed |
| 2702 | +<code>comparable</code> may only be used as type constraints. They cannot be the types of |
| 2703 | +values or variables, or components of other, non-interface types. |
| 2704 | +</p> |
| 2705 | + |
2659 | 2706 | <h3 id="Variable_declarations">Variable declarations</h3>
|
2660 | 2707 |
|
2661 | 2708 | <p>
|
|
0 commit comments