From 0e6a3b24f37a7a00ffe19446f710fee32208ef28 Mon Sep 17 00:00:00 2001 From: Wonder Date: Tue, 17 Mar 2026 16:06:21 +0800 Subject: [PATCH] =?UTF-8?q?Finish:=2003-closures=20-=20=E9=97=AD=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- stage03-functions/03-closures/main.go | 48 +++++++++++++-------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/stage03-functions/03-closures/main.go b/stage03-functions/03-closures/main.go index fe5fb0e..170a755 100644 --- a/stage03-functions/03-closures/main.go +++ b/stage03-functions/03-closures/main.go @@ -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))