Go语言的流程控制包括:
if condition {
// 代码块
} else if condition2 {
// 代码块
} else {
// 代码块
}
// 类似while的用法 for condition { // 代码块 }
// 无限循环 for { // 代码块 }
- **switch-case分支**:
```go
switch variable {
case value1:
// 代码块
case value2:
// 代码块
default:
// 代码块
}
select {
case ch1 <- data:
// 代码块
case data := <-ch2:
// 代码块
default:
// 代码块
}
package main
import (
"fmt"
"time"
)
func main() {
// 成绩等级判断
score := 85
if score >= 90 {
fmt.Println("优秀")
} else if score >= 80 {
fmt.Println("良好")
} else if score >= 60 {
fmt.Println("及格")
} else {
fmt.Println("不及格")
}
// 批量处理订单
orders := []string{"订单1", "订单2", "订单3"}
for i, order := range orders {
fmt.Printf("处理第%d个订单: %s\n", i+1, order)
}
// HTTP状态码处理
statusCode := 200
switch statusCode {
case 200:
fmt.Println("请求成功")
case 404:
fmt.Println("页面未找到")
case 500:
fmt.Println("服务器内部错误")
default:
fmt.Println("其他状态码")
}
// 超时控制
ch := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
ch <- "任务完成"
}()
select {
case msg := <-ch:
fmt.Println(msg)
case <-time.After(1 * time.Second):
fmt.Println("任务超时")
}
}
package main
import "fmt"
func main() {
// switch不带条件表达式
num := 75
switch {
case num >= 90:
fmt.Println("A级")
case num >= 80:
fmt.Println("B级")
default:
fmt.Println("C级")
}
// switch初始化语句
switch day := 3; day {
case 1, 2, 3, 4, 5:
fmt.Println("工作日")
case 6, 7:
fmt.Println("周末")
}
}
package main
import "fmt"
func main() {
// 遍历map
studentScores := map[string]int{
"张三": 90,
"李四": 85,
"王五": 78,
}
for name, score := range studentScores {
fmt.Printf("%s的成绩是: %d\n", name, score)
}
// 遍历字符串(按字符)
str := "Hello世界"
for i, ch := range str {
fmt.Printf("索引%d: 字符%c\n", i, ch)
}
}
本课时我们学习了: