Files
go-basics/stage02-control-flow/02-switch/main.go
T

135 lines
2.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import "fmt"
func exercise1() {
fmt.Println("=== 练习1:基本switch ===")
day := 3
// 使用switch语句,根据day的值输出对应的星期
// 1: 星期一, 2: 星期二, 3: 星期三, 4: 星期四
// 5: 星期五, 6: 星期六, 7: 星期日
// 其他: 无效的天数
switch day {
case 1:
fmt.Println("星期一")
case 2:
fmt.Println("星期二")
case 3:
fmt.Println("星期三")
case 4:
fmt.Println("星期四")
case 5:
fmt.Println("星期五")
case 6:
fmt.Println("星期六")
case 7:
fmt.Println("星期日")
default:
fmt.Println("无效的天数")
}
}
func exercise2() {
fmt.Println("\n=== 练习2:多值匹配 ===")
month := 3
// 使用switch语句,根据month的值输出季节
// 使用多值匹配(一个case匹配多个值)
// 3,4,5: 春季
// 6,7,8: 夏季
// 9,10,11: 秋季
// 12,1,2: 冬季
switch month {
case 3, 4, 5:
fmt.Println("春季")
case 6, 7, 8:
fmt.Println("夏季")
case 9, 10, 11:
fmt.Println("秋季")
case 12, 1, 2:
fmt.Println("冬季")
default:
fmt.Println("无效的月份")
}
}
func exercise3() {
fmt.Println("\n=== 练习3:无表达式的switch ===")
score := 92
// 使用无表达式的switch,根据score判断等级
// 90-100: 优秀
// 80-89: 良好
// 60-79: 及格
// 0-59: 不及格
switch {
case score >= 90 && score <= 100:
fmt.Printf("分数: %d, 等级: 优秀\n", score)
case score >= 80 && score < 90:
fmt.Printf("分数: %d, 等级: 良好\n", score)
case score >= 60 && score < 79:
fmt.Printf("分数: %d, 等级: 及格\n", score)
case score < 60:
fmt.Printf("分数: %d, 等级: 不及格\n", score)
}
}
func exercise4() {
fmt.Println("\n=== 练习4:fallthrough ===")
num := 1
// 使用switch和fallthrough,当num=1时:
// 输出"one"然后继续执行case 2输出"two"
// 提示:在case 1的末尾添加fallthrough
switch num {
case 1:
fmt.Println("one")
fallthrough
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
}
func exercise5() string {
fmt.Println("=== 练习5:switch返回值 ===")
status := 200
// 使用switch语句,根据HTTP状态码返回对应的描述
// 200: OK
// 404: Not Found
// 500: Internal Server Error
// 其他: Unknown Status
var result string
switch status {
case 200:
result = "OK"
case 404:
result = "Not Found"
case 500:
result = "Internal Server Error"
default:
result = "Unknown Status"
}
return result
}
func main() {
fmt.Println("=== switch 练习 ===")
exercise1()
exercise2()
exercise3()
exercise4()
result := exercise5()
fmt.Println(result)
}