比如, case int, float64 编译会报错,有没有什么方法能实现这种用法呢?
```
package main
import "fmt"
func do(i interface{}) {
switch v := i.(type) {
case int, float64: // Illegal! Then how?
fmt.Printf("Twice %v is %v\n", v, v*2)
case string:
fmt.Printf("%q is %v bytes long\n", v, len(v))
default:
fmt.Printf("I don't know about type %T!\n", v)
}
}
func main() {
do(21)
do(3.13)
do("hello")
do(true)
}
```
但是如果是非type类型的switch,是支持多条件判断的,比如
```
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
oss := "golang OS"
switch os := runtime.GOOS; oss {
case "darwin":
fmt.Println("OS X.")
case "golang OS", "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.", os)
}
}
```
#4
更多评论
如果你这里把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