Switch case Different Types with go

huangapple go评论80阅读模式
英文:

Switch case Different Types with go

问题

以下是要翻译的内容:

以下程序由于类型不匹配错误(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 greater than 8")
    }
}

作为一个来自动态类型背景的人,上面的代码有点文化冲击。想知道在Go语言中如何以惯用方式解决这个问题?

英文:

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

得分: 8

只需使用通用的 switch 语句:

func main() {
    i := 5
    switch {
    case i == 4:
        fmt.Println("4")
    case i > 8:
        fmt.Println("i 大于 8")
    default:
        fmt.Printf("i = (%v), i 不等于 4 且 i 小于等于 8\n", i)
    }
}
英文:

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

huangapple
  • 本文由 发表于 2015年8月23日 04:50:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/32160648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定