A1 | A2 | … | An
}
复制代码
甚至还可以在 case 上有新的写法:
case interface {~T}:
复制代码
在支持泛型后,switch 在 type 和 case 上会存在很多种可能性,需要进行具体的特性支持,这个提案就是为此出现。
实际案例
案例一:多类型元素
type Stringish interface {
string | fmt.Stringer
}
func Concat[S Stringish](x []S “S Stringish”) string {
switch type S {
case string:
…
case fmt.Stringer:
…
}
}
复制代码
类型 S 能够支持 string 和 fmt.Stringer 类型,case 配套对应实现。
案例二:近似元素
type Constraint interface {
~int | ~int8 | ~string
}
func ThisSyntax[T Constraint]( “T Constraint”) {
switch type T {
case ~int | ~int8:
…
case ~string:
…
}
}
func IsClearerThanThisSyntax[T Constraint]( “T Constraint”) {
switch type T {
case interface{~int | ~int8 }:
…
case interface{ ~string }:
…
}
}
复制代码
类型 T 可能有很多类型,程序中用到了近似元素,也就是基础类型是 int、int8、string,这些类型中的任何一种都能够满足这个约束。
为此,switch-type 支持了,case 也要配套支持该特性。
争议点
看到这里可能大家也想到了,这个味道很似曾相识,好像某个语法能够支持。因此,这个提案下最有争议的,就是与原有的类型断言的重复。
原有的类型断言如下:
switch T.(type) {
case string:
…
default:
…
}
《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】
复制代码
新的类型判别如下:
switch type T {
case A1:
case A2, A3:
…
}
复制代码
这么咋一看,其实类型断言的完全可以取代新的,那岂不是重复建设,造轮子了?
其实是没有完全取代的。差异点如下: