123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
-
- # More on type sets
- Qinghe
- 21 Jan 2022
-
-
- ## Both elements and methods in constraints
- 约束中可以同时约束元素(具体类型、近似类型、联合类型)和方法。
-
- .code codes/type_sets.go /StringableSignedInteger OMIT/,/StringableSignedInteger OMIT/
-
- 满足这个约束的类型必须满足两个条件:
- 1. 底层类型是int/int8/int16/int32/int64类型其中之一
- 2. 这个类型必须有`String() string`方法
-
- 要注意:
-
- `'~'`符号是必要的,因为int类型本身没有实现`String() string`方法,否则语法检查能通过,但是满足条件的类型集合为空。
-
- ## Composite types in constraints
-
- 复合类型包括以下几种:
-
- - string
- - pointer
- - array
- - slice
- - struct
- - function
- - map
- - channel
-
- ## Composite types in constraints
-
- 在约束中使用复合类型:
-
- .code codes/type_sets.go /COMPOSITE TYPE OMIT/,/COMPOSITE TYPE OMIT/
-
- ## Composite types in constraints
-
- 对于复合类型的使用,有个额外的限制:对于所有的类型集中的类型,只有输入以及输出类型均完全一致的操作才允许使用。
-
- 例如:
-
- .code codes/type_sets.go /COMPOSITE STRUCT FIELD OMIT/,/COMPOSITE STRUCT FIELD OMIT/
-
- (当然目前即使上面例子中各个struct的x字段类型一致也无法执行,因为这个特性在1.18中已经被移除,后续版本中可能会加回来,详情见[issue#50417](https://github.com/golang/go/issues/50417)、[issue#51576](https://github.com/golang/go/issues/51576))
-
-
-
- ## Type conversions
-
- 如果要对两个类型参数From和To类型的变量进行类型转换,则需要From的约束所包含的所有类型均能够转换为To的约束所包含的任一类型。
-
- 例如:
-
- .code codes/type_sets.go /TYPE CONVERSION OMIT/,/TYPE CONVERSION OMIT/
-
-
- ## Untyped constants
- 泛型函数中可能会使用到无类型常量,在使用无类型常量的时候,仅当约束中所包含的所有类型都可以正常使用无类型常量。
-
- .code codes/type_sets.go /UNTYPED CONSTANTS OMIT/,/UNTYPED CONSTANTS OMIT/
-
-
- ## Type sets of embedded constraints
-
-
- ## Interface types in union elements
-
-
- ## Empty type sets
|