Go
package main
import "fmt"
func main() {
var day int
fmt.Println("输入 1 至 7 中的一数字以获取是星期几:")
fmt.Scan(&day)
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
default:
fmt.Println("输入无效,请输入 1 到 7 的数字。")
}
}
在 Go 中,fallthrough 允许继续执行下一个 case,即使条件不满足:
Go
package main
import "fmt"
func main() {
var value int
fmt.Println("输入 1 到 3 的数字:")
fmt.Scan(&value)
switch value {
case 1:
fmt.Println("This is 1")
fallthrough
case 2:
fmt.Println("This is 2")
case 3:
fmt.Println("This is 3")
default:
fmt.Println("输入无效,请输入 1 到 3 的数字。")
}
}
如果多个 case 如果逻辑相同,可以合并:
Go
package main
import "fmt"
func main() {
var value int
fmt.Println("输入 1 至 5 中的一个数字:")
fmt.Scan(&value)
switch value {
case 1, 2, 3:
fmt.Println("This is either 1, 2, or 3")
case 4:
fmt.Println("This is 4")
case 5:
fmt.Println("This is 5")
default:
fmt.Println("Other number")
}
}
Go 的 switch 还有一种特殊形式:
bash
switch value := x.(type) {}
Type Switch,类型 switch,它通常配合接口使用。
Go
package main
import "fmt"
func printType(value interface{}) {
switch v := value.(type) {
case int:
fmt.Println("整数:", v)
case string:
fmt.Println("字符串:", v)
case bool:
fmt.Println("布尔值:", v)
case float64:
fmt.Println("浮点数:", v)
default:
fmt.Println("其他类型")
}
}
func main() {
printType(55)
printType("Golang")
printType(true)
printType(3.1415)
}