Golang教程:(十)switch 语句
原文:https://golangbot.com/switch/ 这是本Golang系列教程的第十篇。
举例是说明问题最好的方式,让我们写一个简单的程序,输入手指编号,输出对应的手指名称:)。例如 0 表示拇指,1 表示食指等。 package main
import (
"fmt"
)
func main() {
finger := 4
switch finger {
case 1:
fmt.Println("Thumb")
case 2:
fmt.Println("Index")
case 3:
fmt.Println("Middle")
case 4:
fmt.Println("Ring")
case 5:
fmt.Println("Pinky")
}
}
在上面的程序中, 多个有相同值的 package main
import (
"fmt"
)
func main() {
finger := 4
switch finger {
case 1:
fmt.Println("Thumb")
case 2:
fmt.Println("Index")
case 3:
fmt.Println("Middle")
case 4:
fmt.Println("Ring")
case 4://duplicate case
fmt.Println("Another Ring")
case 5:
fmt.Println("Pinky")
}
}
default case我们每只手只有 5 根手指,但是如果我们输入一个错误的手指序号会发生什么呢?这里就要用到 package main
import (
"fmt"
)
func main() {
switch finger := 8; finger {//finger is declared in switch
case 1:
fmt.Println("Thumb")
case 2:
fmt.Println("Index")
case 3:
fmt.Println("Middle")
case 4:
fmt.Println("Ring")
case 5:
fmt.Println("Pinky")
default: //default case
fmt.Println("incorrect finger number")
}
}
在上面的程序中, 你也许发现了另外一个小的改变,就是将 包含多个表达式的 case可以在一个 package main
import (
"fmt"
)
func main() {
letter := "i"
switch letter {
case "a","e","i","o","u": //multiple expressions in case
fmt.Println("vowel")
default:
fmt.Println("not a vowel")
}
}
上面的程序检测 没有表达式的 switch
package main
import (
"fmt"
)
func main() {
num := 75
switch { // expression is omitted
case num >= 0 && num <= 50:
fmt.Println("num is greater than 0 and less than 50")
case num >= 51 && num <= 100:
fmt.Println("num is greater than 51 and less than 100")
case num >= 101:
fmt.Println("num is greater than 100")
}
}
在上面的程序中, fallthrough在 Go 中执行完一个 让我们写一个程序来了解 package main
import (
"fmt"
)
func number() int {
num := 15 * 5
return num
}
func main() {
switch num := number(); { //num is not a constant
case num < 50:
fmt.Printf("%d is lesser than 50n",num)
fallthrough
case num < 100:
fmt.Printf("%d is lesser than 100n",num)
fallthrough
case num < 200:
fmt.Printf("%d is lesser than 200",num)
}
}
75 is lesser than 100
75 is lesser than 200
还有一种
目录 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |