带 go 的 Switch case 不同类型

由于类型不匹配错误(int vs bool),以下程序无法编译


package main


import "fmt"


func main() {

    i := 5

    switch i {

    case 4:

        fmt.Println("4")

    case i > 8:

        fmt.Println("i is greator than 8")

    }

}

作为来自动态打字背景的人,以上这有点文化冲击。所以想知道在 GO 中这样做的惯用方法是什么?


繁花如伊
浏览 171回答 1
1回答

慕后森

只需使用通用开关:func main() {&nbsp; &nbsp; i := 5&nbsp; &nbsp; switch {&nbsp; &nbsp; case i == 4:&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("4")&nbsp; &nbsp; case i > 8:&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("i is greator than 8")&nbsp; &nbsp; default:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("i = (%v), i != 4 && i <= 8\n", i)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go