第三章:流程控制

第三章:流程控制

3.1 条件语句

if语句

go 复制代码
package main

import "fmt"

func main() {
    score := 85

    // 基本if语句
    if score >= 60 {
        fmt.Println("及格")
    }

    // if-else语句
    if score >= 90 {
        fmt.Println("优秀")
    } else {
        fmt.Println("还需努力")
    }

    // if-else if-else语句
    if score >= 90 {
        fmt.Println("优秀")
    } else if score >= 80 {
        fmt.Println("良好")
    } else if score >= 70 {
        fmt.Println("中等")
    } else if score >= 60 {
        fmt.Println("及格")
    } else {
        fmt.Println("不及格")
    }

    // if语句带初始化语句
    if num := 10; num%2 == 0 {
        fmt.Printf("%d是偶数\n", num)
    } else {
        fmt.Printf("%d是奇数\n", num)
    }
}

switch语句

go 复制代码
package main

import (
    "fmt"
    "time"
)

func main() {
    // 基本switch
    day := time.Now().Weekday()

    switch day {
    case time.Monday:
        fmt.Println("星期一")
    case time.Tuesday:
        fmt.Println("星期二")
    case time.Wednesday:
        fmt.Println("星期三")
    case time.Thursday:
        fmt.Println("星期四")
    case time.Friday:
        fmt.Println("星期五")
    case time.Saturday, time.Sunday:
        fmt.Println("周末")
    default:
        fmt.Println("未知")
    }

    // 多条件匹配
    month := time.Now().Month()
    switch month {
    case time.March, time.April, time.May:
        fmt.Println("春天")
    case time.June, time.July, time.August:
        fmt.Println("夏天")
    case time.September, time.October, time.November:
        fmt.Println("秋天")
    case time.December, time.January, time.February:
        fmt.Println("冬天")
    }

    // 无条件switch
    score := 85
    switch {
    case score >= 90:
        fmt.Println("优秀")
    case score >= 80:
        fmt.Println("良好")
    case score >= 70:
        fmt.Println("中等")
    case score >= 60:
        fmt.Println("及格")
    default:
        fmt.Println("不及格")
    }

    // 类型switch
    var x interface{} = "hello"
    switch v := x.(type) {
    case int:
        fmt.Printf("x是int: %d\n", v)
    case string:
        fmt.Printf("x是string: %s\n", v)
    case bool:
        fmt.Printf("x是bool: %v\n", v)
    default:
        fmt.Printf("x是未知类型: %T\n", v)
    }

    // fallthrough关键字
    num := 1
    switch num {
    case 1:
        fmt.Println("一")
        fallthrough
    case 2:
        fmt.Println("二")
        fallthrough
    case 3:
        fmt.Println("三")
    }
    // 输出: 一 二 三
}

3.2 循环语句

for循环

go 复制代码
package main

import "fmt"

func main() {
    // 基本for循环
    fmt.Println("基本for循环:")
    for i := 1; i <= 5; i++ {
        fmt.Printf("%d ", i)
    }
    fmt.Println()

    // while风格循环
    fmt.Println("while风格循环:")
    count := 1
    for count <= 5 {
        fmt.Printf("%d ", count)
        count++
    }
    fmt.Println()

    // 无限循环
    fmt.Println("无限循环 (使用break退出):")
    sum := 0
    for {
        sum += 1
        if sum > 5 {
            break
        }
        fmt.Printf("%d ", sum)
    }
    fmt.Println()

    // range遍历数组
    fmt.Println("range遍历数组:")
    arr := []int{10, 20, 30, 40, 50}
    for index, value := range arr {
        fmt.Printf("索引: %d, 值: %d\n", index, value)
    }

    // range遍历字符串
    fmt.Println("range遍历字符串:")
    str := "Hello, 世界"
    for i, ch := range str {
        fmt.Printf("索引: %d, 字符: %c\n", i, ch)
    }

    // range遍历map
    fmt.Println("range遍历map:")
    scores := map[string]int{
        "张三": 90,
        "李四": 85,
        "王五": 95,
    }
    for name, score := range scores {
        fmt.Printf("姓名: %s, 分数: %d\n", name, score)
    }

    // range遍历channel
    fmt.Println("range遍历channel:")
    ch := make(chan int, 3)
    ch <- 1
    ch <- 2
    ch <- 3
    close(ch)
    for v := range ch {
        fmt.Printf("%d ", v)
    }
    fmt.Println()
}

break和continue

go 复制代码
package main

import "fmt"

func main() {
    // break示例
    fmt.Println("break示例:")
    for i := 1; i <= 10; i++ {
        if i > 5 {
            break
        }
        fmt.Printf("%d ", i)
    }
    fmt.Println()

    // continue示例
    fmt.Println("continue示例 (跳过偶数):")
    for i := 1; i <= 10; i++ {
        if i%2 == 0 {
            continue
        }
        fmt.Printf("%d ", i)
    }
    fmt.Println()

    // 带标签的break
    fmt.Println("带标签的break:")
    outer:
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            if i == 2 && j == 2 {
                break outer
            }
            fmt.Printf("(%d,%d) ", i, j)
        }
    }
    fmt.Println()

    // 带标签的continue
    fmt.Println("带标签的continue:")
    outer2:
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            if j == 2 {
                continue outer2
            }
            fmt.Printf("(%d,%d) ", i, j)
        }
    }
    fmt.Println()
}

3.3 goto语句

go 复制代码
package main

import "fmt"

func main() {
    i := 0

loop:
    if i < 5 {
        fmt.Printf("%d ", i)
        i++
        goto loop
    }
    fmt.Println()
}

3.4 defer语句

go 复制代码
package main

import "fmt"

func main() {
    // defer基本用法
    fmt.Println("开始")
    defer fmt.Println("defer 1")
    defer fmt.Println("defer 2")
    defer fmt.Println("defer 3")
    fmt.Println("结束")
    // 输出顺序: 开始 结束 defer 3 defer 2 defer 1

    // defer用于资源清理
    fmt.Println("\n文件操作示例:")
    fmt.Println("打开文件")
    defer fmt.Println("关闭文件")
    fmt.Println("读取文件")
    fmt.Println("处理数据")

    // defer与匿名函数
    fmt.Println("\ndefer与匿名函数:")
    x := 10
    defer func() {
        fmt.Printf("defer中的x: %d\n", x)
    }()
    x = 20
    fmt.Printf("修改后的x: %d\n", x)

    // defer执行顺序
    fmt.Println("\ndefer执行顺序:")
    for i := 0; i < 5; i++ {
        defer fmt.Printf("%d ", i)
    }
    fmt.Println()
}

3.5 实战案例:成绩统计系统

go 复制代码
package main

import (
    "fmt"
    "sort"
)

// Student 学生结构体
type Student struct {
    Name  string
    Score int
}

func main() {
    // 学生成绩数据
    students := []Student{
        {"张三", 90},
        {"李四", 85},
        {"王五", 95},
        {"赵六", 78},
        {"钱七", 92},
        {"孙八", 88},
        {"周九", 76},
        {"吴十", 98},
    }

    // 统计信息
    var totalScore int
    maxScore := students[0].Score
    minScore := students[0].Score
    maxStudent := students[0].Name
    minStudent := students[0].Name

    // 成绩等级统计
    gradeCount := map[string]int{
        "优秀": 0,
        "良好": 0,
        "中等": 0,
        "及格": 0,
        "不及格": 0,
    }

    // 遍历统计
    for _, student := range students {
        totalScore += student.Score

        // 更新最高分和最低分
        if student.Score > maxScore {
            maxScore = student.Score
            maxStudent = student.Name
        }
        if student.Score < minScore {
            minScore = student.Score
            minStudent = student.Name
        }

        // 统计等级
        switch {
        case student.Score >= 90:
            gradeCount["优秀"]++
        case student.Score >= 80:
            gradeCount["良好"]++
        case student.Score >= 70:
            gradeCount["中等"]++
        case student.Score >= 60:
            gradeCount["及格"]++
        default:
            gradeCount["不及格"]++
        }
    }

    // 计算平均分
    avgScore := float64(totalScore) / float64(len(students))

    // 按成绩排序
    sortedStudents := make([]Student, len(students))
    copy(sortedStudents, students)
    sort.Slice(sortedStudents, func(i, j int) bool {
        return sortedStudents[i].Score > sortedStudents[j].Score
    })

    // 输出结果
    fmt.Println("=" + strings.Repeat("=", 50))
    fmt.Println("学生成绩统计系统")
    fmt.Println("=" + strings.Repeat("=", 50))

    fmt.Printf("\n学生总数: %d\n", len(students))
    fmt.Printf("总分: %d\n", totalScore)
    fmt.Printf("平均分: %.2f\n", avgScore)
    fmt.Printf("最高分: %d (%s)\n", maxScore, maxStudent)
    fmt.Printf("最低分: %d (%s)\n", minScore, minStudent)

    fmt.Println("\n成绩等级分布:")
    for grade, count := range gradeCount {
        if count > 0 {
            percentage := float64(count) / float64(len(students)) * 100
            fmt.Printf("  %s: %d人 (%.1f%%)\n", grade, count, percentage)
        }
    }

    fmt.Println("\n成绩排名:")
    for i, student := range sortedStudents {
        fmt.Printf("  第%d名: %s - %d分\n", i+1, student.Name, student.Score)
    }
    fmt.Println("=" + strings.Repeat("=", 50))
}
相关推荐
程序员爱钓鱼1 天前
Go 类型转换详解
后端·面试·go
朦胧之1 天前
Go 基础
后端·go
似璟如你2 天前
Java 开发者的 Go 语法基础:从 0 开始快速上手 Go
java·开发语言·后端·golang·go·编程语言
用户857822698122 天前
Golang 从 gin 的启动到 net/http 标准库的 HTTP/1.1, HTTP/2 协议基本流程
go
logomister设计公司阿燕2 天前
个人做商标设计注册最快多久能拿受理号?
go
妙码生花2 天前
从 PHP 到 AI + Golang,程序员自救转型手记(五十八):后台系统配置管理实现
前端·后端·go
小满zs3 天前
Go语言第七章(Map)
后端·go
设计总监老谢3 天前
初创公司商标设计注册拿到证要等多久?
go
用户125758524363 天前
为什么队列长度归零,不代表后台异步任务真的跑完了
redis·后端·go