在本教程中,您将学习如何使用switch-case语句根据Golang中的不同条件执行不同的操作。
Golang 还支持类似于其他语言(如Php或Java)中的 switch 语句。switch 语句是一种替代方法,用于根据变量的状态将冗长的 if else 比较表达为更具可读性的代码。
switch语句
switch语句用于选择要执行的多个代码块之一。
请考虑以下示例,该示例显示特定日期的不同消息。
package main
import (
"fmt"
"time"
)
func main() {
today := time.Now()
switch today.Day() {
case 5:
fmt.Println("Today is 5th. Clean your house.")
case 10:
fmt.Println("Today is 10th. Buy some wine.")
case 15:
fmt.Println("Today is 15th. Visit a doctor.")
case 25:
fmt.Println("Today is 25th. Buy some food.")
case 31:
fmt.Println("Party tonight.")
default:
fmt.Println("No information available for that day.")
}
}
如果未找到匹配项,则使用default语句。
case拥有多个条件
case带有多个条件,用于为许多类似情况选择公共代码块。
package main
import (
"fmt"
"time"
)
func main() {
today := time.Now()
var t int = today.Day()
switch t {
case 5, 10, 15:
fmt.Println("Clean your house.")
case 25, 26, 27:
fmt.Println("Buy some food.")
case 31:
fmt.Println("Party tonight.")
default:
fmt.Println("No information available for that day.")
}
}
fallthrough关键字
fallthrough关键字,用于强制执行流通过连续的事例块。
package main
import (
"fmt"
"time"
)
func main() {
today := time.Now()
switch today.Day() {
case 5:
fmt.Println("Clean your house.")
fallthrough
case 10:
fmt.Println("Buy some wine.")
fallthrough
case 15:
fmt.Println("Visit a doctor.")
fallthrough
case 25:
fmt.Println("Buy some food.")
fallthrough
case 31:
fmt.Println("Party tonight.")
default:
fmt.Println("No information available for that day.")
}
}
下面是每月 10 日的输出。
Buy some wine.
Visit a doctor.
Buy some food.
Party tonight.
有条件case
case语句还可以与条件运算符一起使用。
package main
import (
"fmt"
"time"
)
func main() {
today := time.Now()
switch {
case today.Day() < 5:
fmt.Println("Clean your house.")
case today.Day() <= 10:
fmt.Println("Buy some wine.")
case today.Day() > 15:
fmt.Println("Visit a doctor.")
case today.Day() == 25:
fmt.Println("Buy some food.")
default:
fmt.Println("No information available for that day.")
}
}
switch初始值设定项语句
switch关键字可以紧跟一个简单的初始化语句,其中可以声明和初始化switch代码块的本地变量。
package main
import (
"fmt"
"time"
)
func main() {
switch today := time.Now(); {
case today.Day() < 5:
fmt.Println("Clean your house.")
case today.Day() <= 10:
fmt.Println("Buy some wine.")
case today.Day() > 15:
fmt.Println("Visit a doctor.")
case today.Day() == 25:
fmt.Println("Buy some food.")
default:
fmt.Println("No information available for that day.")
}
}