1. 常用switch, 一个case 多个条件, 默认情况下 case 最后自带 break 语句,匹配成功后就不会执行其他 case
var lang string
lang = "js"
//常用switch, 一个case 多个条件, 默认情况下 case 最后自带 break 语句,匹配成功后就不会执行其他 case
switch lang {
case "java":
println("this case is java")
case "go", "js":
println("this case is go")
println("this case also is js")
case "php":
println("this case is php")
default:
println("this case is python")
}
//输出结果
//this case is go
//this case also is js
2. fallthrough 会强制执行后面的 case 语句,fallthrough 不会判断下一条 case 的表达式结果是否为 true。
var lang string
lang = "js"
switch lang {
case "java":
println("this case is java")
case "go", "js":
println("this case is go")
println("this case also is js")
fallthrough
case "php":
println("this case is php")
default:
println("this case is python")
}
//输出结果
//this case is go
//this case also is js
//this case is php
3. 类型判断
var x interface{}
switch i:= x.(type) {
case int:
fmt.Printf("x type is %T", i)
case string:
fmt.Printf("x type is %T", i)
case bool, nil:
fmt.Printf("x type is %T", i)
}
//输出结果
//x type is <nil>
代码地址:https://github.com/hufeng903/go-demo/tree/master/switch

本文介绍了Go语言中switch语句的使用,包括如何在一个case中设置多个条件,以及fallthrough关键字的运用,它使得代码会继续执行下一个case,即使已经匹配成功。同时,文章还展示了如何利用switch进行类型判断。示例代码展示了不同情况下的输出结果,帮助读者理解fallthrough的工作原理。
641

被折叠的 条评论
为什么被折叠?



