Golang 使用switch和多值case
Switch 语句是一种多路分支,它提供了与冗长的if-else比较的另一种选择。它根据表达式的值或单个变量的状态从多个块列表中选择要执行的单个块。使用具有多个值的case的switch语句对应于在单个case中使用 多个值。 这是通过用逗号分隔case中的多个值来实现的。
示例1:
// Golang program to illustrate the
// use of switch with multiple value cases
package main
import (
"fmt"
)
func main() {
// 接收用户输入的月份
var month string
fmt.Scanln(&month)
// 预测输入月份的季节
// 每个switch case都有多个值
switch month {
case "january", "december":
fmt.Println("冬季。")
case "february", "march":
fmt.Println("春季。")
case "april", "may", "june":
fmt.Println("夏季。")
case "july", "august":
fmt.Println("季风雨季。")
case "september", "november":
fmt.Println("秋季。")
}
}
输入: january
输出: 冬季。
输入: september
输出: 秋季。
与为具有相同季节的月份编写不同的单个case相比,我们将具有相同输出的不同月份分为一组。这样可以节省冗余的代码。
示例2:
// Golang program to illustrate the
// use of switch with multiple value cases
package main
import (
"fmt"
)
func main() {
// 整数输入以从用户(只有1-10)判断奇偶性
var number int
fmt.Scanln(&number)
// 预测输入数字是偶数还是奇数
// 每个switch case都有多个值
switch number {
case 2, 4, 6, 8, 10:
fmt.Println("您输入了一个偶数。")
case 1, 3, 5, 7, 9:
fmt.Println("您输入了一个奇数。")
}
}
输入: 6
输出: 您输入了一个偶数。
输入: 5
输出: 您输入了一个奇数。
与编写10个不同的case来检查输入数字是否为偶数相比,我们可以使用具有多个case值的2个switch case来完成相同的操作。
示例3:
//Golang程序来说明使用
//带有多个值的switch case
package main
import (
"fmt"
)
func main() {
// 字符输入(a-z或A-Z)
var alphabet string
fmt.Scanln(&alphabet)
// 预测字符是大写还是小写
// 每个switch case都有多个值
switch alphabet {
case "a", "b", "c", "d", "e", "f", "g", "h", "i",
"j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z":
fmt.Println("小写字母字符。")
case "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z":
fmt.Println("大写字母字符。")
}
}
输入: g
输出: 小写字母字符。
输入: F
输出: 大写字母字符。