如何在switch中对多个type进行匹配

kooder · · 3776 次点击
- case 匹配单个类型:case下面的语句可以将a当做此类型操作 - case 匹配多个类型:只能以i声明的类型进行操作,譬如如果声明的是interface{} 那就不能使用 len() ## 搬运: - https://stackoverflow.com/questions/40575033/golang-multiple-case-in-type-switch - https://golang.org/ref/spec#Type_switches ``` The TypeSwitchGuard may include a short variable declaration. When that form is used, the variable is declared at the beginning of the implicit block in each clause. In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the type of the expression in the TypeSwitchGuard. ``` 只能说,主动适应golang强类型语言的思维方式……(或者等泛型)
#6
更多评论
不能偷懒,老老实实分开呗。
#1
如果你这里把int和float64分到同一组是出于有相同的算数操作,那么可以考虑把这些操作归类到一个interface,然后将int和float64再自定义类型,`type MyInt int`,`type MyFloat64 float64`, 然后将MyInt和MyFloat64实现这个interface的接口,这样上面就可以统一为 : case MyInterface: fmt.Printf("Twice %v is %v\n", v, v.Multiply(2))
#2