我们只有5根手指,如果我们输入了错误的手指号会发生什么? 这可以通过Default case
(缺省情况)来处理。当其他case
都不匹配时,将执行Default case
(缺省情况)。
package main
import (
"fmt"
)
func main() {
switch finger := 8; 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")
default: //default case
fmt.Println("incorrect finger number")
}
}
在上面的程序中,手指号是8
时,不匹配任何case
,因此执行default
下的代码。 default
不一定放在最后,它可以出现在switch
语句中的任何地方。
你可能还注意到finger
变量在switch
语句中声明。switch
语句可以包含一个可省略语句,它在表达式求值之前执行,此处声明的finger
变量作用域,仅限于switch
语句包含的代码块。