douya7282 2015-08-22 20:50
浏览 12
已采纳

随身带开关盒不同类型

The following program doesn't compile due to type mismatch error(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")
    }
}

As someone from Dynamic Typing background, this the above is bit of a culture shock. so wondering what's the idiomatic way do this in GO?

  • 写回答

1条回答 默认 最新

  • drob50257447 2015-08-22 20:55
    关注

    Just use a generic switch:

    func main() {
        i := 5
        switch {
        case i == 4:
            fmt.Println("4")
        case i > 8:
            fmt.Println("i is greator than 8")
        default: 
            fmt.Printf("i = (%v), i != 4 && i <= 8
    ", i)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?