Açıklama Yok

chapter3-others-about-generics.slide 2.1KB

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