英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论