go - 开关盒不同类型与去

标签 go switch-statement

由于类型不匹配错误(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 中执行此操作的惯用方法是什么?

最佳答案

只需使用通用开关:

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\n", i)
    }
}

关于go - 开关盒不同类型与去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32160648/

相关文章:

methods - 重命名类型后,我无法访问其某些方法

go - 使用字节包而不是字符串有什么好处?

c++ - Switch case 总是显示 Default case

C - 具有多个案例编号的开关

c# - 具有底层字节类型的枚举在开关中失败

json - 在 Go 中处理 JSON Post 请求 - 错误

pointers - 如何在不指定类型的情况下修改函数输入参数?

go - 创建未知类型的 slice ?

c - 在开关盒中将 int 与 int 数组的元素匹配

c++ - 如果我们在需要整数的 switch case 中输入一个字符会发生什么