Finish: 04-defer - defer机制
This commit is contained in:
@@ -6,7 +6,7 @@ func exercise1() {
|
|||||||
fmt.Println("=== 练习1:defer基本用法 ===")
|
fmt.Println("=== 练习1:defer基本用法 ===")
|
||||||
|
|
||||||
// 使用defer,在函数结束时打印"函数结束"
|
// 使用defer,在函数结束时打印"函数结束"
|
||||||
____
|
defer fmt.Println("函数结束")
|
||||||
fmt.Println("函数执行中")
|
fmt.Println("函数执行中")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -15,9 +15,9 @@ func exercise2() {
|
|||||||
|
|
||||||
// 使用多个defer语句,按照1-2-3的顺序声明
|
// 使用多个defer语句,按照1-2-3的顺序声明
|
||||||
// 观察输出的顺序(应该是3-2-1)
|
// 观察输出的顺序(应该是3-2-1)
|
||||||
____
|
defer fmt.Print(1)
|
||||||
____
|
defer fmt.Print(2)
|
||||||
____
|
defer fmt.Print(3)
|
||||||
fmt.Println("正常执行")
|
fmt.Println("正常执行")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,13 +27,13 @@ func exercise3() int {
|
|||||||
// 使用具名返回值result
|
// 使用具名返回值result
|
||||||
// defer函数中将result修改为100
|
// defer函数中将result修改为100
|
||||||
// return返回50
|
// return返回50
|
||||||
var ____ int = ____
|
var result int = 100
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
____ = ____
|
result = 50
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return ____
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
func exercise4() {
|
func exercise4() {
|
||||||
@@ -43,7 +43,7 @@ func exercise4() {
|
|||||||
|
|
||||||
// 使用defer打印i的值
|
// 使用defer打印i的值
|
||||||
// 注意:defer声明时就对参数求值了
|
// 注意:defer声明时就对参数求值了
|
||||||
____
|
defer fmt.Println(i)
|
||||||
|
|
||||||
i = 10
|
i = 10
|
||||||
fmt.Println("修改i为:", i)
|
fmt.Println("修改i为:", i)
|
||||||
@@ -58,7 +58,7 @@ func exercise5() {
|
|||||||
|
|
||||||
// 使用defer在函数结束时关闭资源
|
// 使用defer在函数结束时关闭资源
|
||||||
defer func() {
|
defer func() {
|
||||||
fmt.Println("关闭:", ____)
|
fmt.Println("关闭:", resource)
|
||||||
}()
|
}()
|
||||||
|
|
||||||
fmt.Println("使用:", resource)
|
fmt.Println("使用:", resource)
|
||||||
@@ -71,15 +71,15 @@ func exercise6() {
|
|||||||
// 每个defer捕获当前i的值并打印
|
// 每个defer捕获当前i的值并打印
|
||||||
// 提示:使用闭包或立即求值
|
// 提示:使用闭包或立即求值
|
||||||
for i := 1; i <= 3; i++ {
|
for i := 1; i <= 3; i++ {
|
||||||
____ func(n int) {
|
defer func(n int) {
|
||||||
fmt.Printf("defer输出: %d\n", n)
|
fmt.Printf("defer输出: %d\n", n)
|
||||||
}(____)
|
}(i)
|
||||||
fmt.Println("循环输出:", i)
|
fmt.Println("循环输出:", i)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
fmt.Println("=== defer 练习 ===\n")
|
fmt.Println("=== defer 练习 ===")
|
||||||
|
|
||||||
exercise1()
|
exercise1()
|
||||||
exercise2()
|
exercise2()
|
||||||
|
|||||||
Reference in New Issue
Block a user