在 switch case 的帮助下,我们可以实现尽可能多的 if 语句的功能。在 Golang 中,switch case 可以处理字符串、包括整数值和浮点值在内的变量列表。
句法:
switch optstatement; optexpression{
case expression1: Statement..
case expression2: Statement..
…
default: Statement..
}
示例 1:在这个示例中,我们可以看到通过使用 switch case 并假设变量为字符串类型,我们可以使用 switch case。
// Golang program that uses string switch
package main
// Here "fmt" is formatted IO which
// is same as C’s printf and scanf.
import "fmt"
// Main function
func main() {
day := "Tue"
// Use switch on the day variable.
switch {
case day == "Mon":
fmt.Println("Monday")
case day == "Tue":
fmt.Println("Tuesday")
case day == "Wed":
fmt.Println("Wednesday")
}
}
输出 :
Tuesday
示例 2:
// Golang program that uses string switch
package main
// Here "fmt" is formatted IO which
// is same as C’s printf and scanf.
import "fmt"
// Main function
func main() {
gfg := "Geek"
// Use switch on the day variable.
switch {
case gfg == "Geek":
fmt.Println("Geek")
case gfg == "For":
fmt.Println("For")
case gfg == "Geeks":
fmt.Println("Geeks")
}
}
输出:
Geek