Files
go-basics/stage02-control-flow/04-defer/main.go
T
2026-03-17 15:37:09 +08:00

91 lines
1.7 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:defer基本用法 ===")
// 使用defer,在函数结束时打印"函数结束"
defer fmt.Println("函数结束")
fmt.Println("函数执行中")
}
func exercise2() {
fmt.Println("\n=== 练习2:defer执行顺序 ===")
// 使用多个defer语句,按照1-2-3的顺序声明
// 观察输出的顺序(应该是3-2-1)
defer fmt.Print(1)
defer fmt.Print(2)
defer fmt.Print(3)
fmt.Println("正常执行")
}
func exercise3() int {
fmt.Println("\n=== 练习3:defer修改返回值 ===")
// 使用具名返回值result
// defer函数中将result修改为100
// return返回50
var result int = 100
defer func() {
result = 50
}()
return result
}
func exercise4() {
fmt.Println("\n=== 练习4:defer参数求值 ===")
i := 0
// 使用defer打印i的值
// 注意:defer声明时就对参数求值了
defer fmt.Println(i)
i = 10
fmt.Println("修改i为:", i)
}
func exercise5() {
fmt.Println("\n=== 练习5:实际场景 - 模拟资源管理 ===")
// 模拟打开资源
resource := "文件句柄"
fmt.Println("打开:", resource)
// 使用defer在函数结束时关闭资源
defer func() {
fmt.Println("关闭:", resource)
}()
fmt.Println("使用:", resource)
}
func exercise6() {
fmt.Println("\n=== 练习6:defer捕获变量的值 ===")
// 使用循环声明多个defer
// 每个defer捕获当前i的值并打印
// 提示:使用闭包或立即求值
for i := 1; i <= 3; i++ {
defer func(n int) {
fmt.Printf("defer输出: %d\n", n)
}(i)
fmt.Println("循环输出:", i)
}
}
func main() {
fmt.Println("=== defer 练习 ===")
exercise1()
exercise2()
fmt.Printf("练习3返回值: %d\n", exercise3())
exercise4()
exercise5()
exercise6()
}