Switch语句是一种多路分支,它提供了一种替代方法,该方法过于冗长的 if-else 比较。它根据表达式的值或单个变量的状态从多个块的列表中选择要执行的单个块。使用多个值 case 的 switch 语句对应于在单个 case 中使用多个值。这是通过用逗号分隔案例中的多个值来实现的。
示例 1:
// Golang program to illustrate the
// use of switch with multiple value cases
package main
import (
"fmt"
)
func main() {
// string to input month from user
var month string
fmt.Scanln(&month)
// switch case for predicting
// seasons for month entered
// each switch case has more
// than one values
switch month {
case "january", "december":
fmt.Println("Winter.")
case "february", "march":
fmt.Println("Spring.")
case "april", "may", "june":
fmt.Println("Summer.")
case "july", "august":
fmt.Println("Monsoon.")
case "september", "november":
fmt.Println("Autumn.")
}
}
Input : january
Output : Winter.
Input : september
Output : Autumn.
我们没有在同一季节的几个月内制作不同的个别案例,而是用相同的产量在不同的月份进行。这节省了我们编写冗余代码段的时间。
示例 2:
// Golang program to illustrate the
// use of switch with multiple value cases
package main
import (
"fmt"
)
func main() {
// integer to input number from
// user (only 1-10)
var number int
fmt.Scanln(&number)
// switch case for predicting
// whether the number is even or odd
// each switch case has more
// than one values
switch number {
case 2, 4, 6, 8, 10:
fmt.Println("You entered an even number.")
case 1, 3, 5, 7, 9:
fmt.Println("You entered an odd number.")
}
}
Input : 6
Output : You entered an even number.
Input : 5
Output : You entered an odd number.
与其编写 10 个不同的 case 来检查输入的数字是否为偶数,我们可以简单地使用多个 case 值在 2 个 switch case 中执行相同的操作。
示例 3:
// Golang program to illustrate the
// use of switch with multiple value cases
package main
import (
"fmt"
)
func main() {
// character input (a-z or A-Z)
var alphabet string
fmt.Scanln(&alphabet)
// switch case for predicting
// whether the character is
// uppercase or lowercase
// each switch case has more
// than one values
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("Lowercase alphabet character.")
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("Uppercase alphabet character.")
}
}
Input : g
Output : Lowercase alphabet character.
Input : F
Output : Uppercase alphabet character.