Finish: 03-closures - 闭包

This commit is contained in:
2026-03-17 16:06:21 +08:00
parent 9b6e6badaa
commit 0e6a3b24f3
+24 -24
View File
@@ -9,11 +9,11 @@ func exercise1() func(int) int {
// 该闭包接收一个int参数并返回乘以multiplier的结果
multiplier := 3
____ := func(num int) ____ {
return ____
multifunc := func(num int) int {
return multiplier * num
}
return ____
return multifunc
}
func exercise2() func() int {
@@ -23,14 +23,14 @@ func exercise2() func() int {
// 每次调用返回的函数时,计数器加1
// 提示:使用匿名函数捕获外部变量
count := ____
count := 0
____ := func() ____ {
____
return ____
countfunc := func() int {
count++
return count
}
return ____
return countfunc
}
func exercise3() func() int {
@@ -40,15 +40,15 @@ func exercise3() func() int {
// 每次调用返回下一个斐波那契数
// 数列: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...
a, b := ____, ____
a, b := 0, 1
____ := func() ____ {
result := ____
a, b = ____
return ____
fib := func() int {
result := a
a, b = b, a+b
return result
}
return ____
return fib
}
func exercise4() func(int) bool {
@@ -59,13 +59,13 @@ func exercise4() func(int) bool {
// 检查函数判断输入数字是否在[min, max]范围内
min := 10
max := ____
max := 20
____ := func(num int) ____ {
return num >= ____ && num <= ____
check := func(num int) bool {
return num >= min && num <= max
}
return ____
return check
}
func exercise5(start int) func(int) int {
@@ -75,18 +75,18 @@ func exercise5(start int) func(int) int {
// 从start开始,每次调用累加参数值
// 提示:闭包应该能访问外部作用域的变量
total := ____
total := start
____ := func(n int) ____ {
____
return ____
adder := func(n int) int {
total += n
return total
}
return ____
return adder
}
func main() {
fmt.Println("=== 闭包 练习 ===\n")
fmt.Println("=== 闭包 练习 ===")
add3 := exercise1()
fmt.Printf("练习1结果: add3(4) = %d\n", add3(4))