diff --git a/examples/recursion/recursion.go b/examples/recursion/recursion.go index a88b1e5..fbc022b 100644 --- a/examples/recursion/recursion.go +++ b/examples/recursion/recursion.go @@ -17,4 +17,21 @@ func fact(n int) int { func main() { fmt.Println(fact(7)) + + // Closures can also be recursive, but this requires the + // closure to be declared with a typed `var` explicitly + // before it's defined. + var fib func(n int) int + + fib = func(n int) int { + if n < 2 { + return n + } + return fib(n-1) + fib(n-2) + + // Since `fib` was previously declared in `main`, Go + // knows which function to call with `fib` here. + } + + fmt.Println(fib(7)) } diff --git a/examples/recursion/recursion.hash b/examples/recursion/recursion.hash index ac2db78..2a19ed1 100644 --- a/examples/recursion/recursion.hash +++ b/examples/recursion/recursion.hash @@ -1,2 +1,2 @@ -9bfb2f870007082835a3c0efaac9aa1c3bc2c15c -smWim1q9ofu +55d9633a4f0fd0eac2f243b2a2ddb35ae91ed4a9 +LnBMavPrkuf diff --git a/examples/recursion/recursion.sh b/examples/recursion/recursion.sh index 53b8e15..ac85484 100644 --- a/examples/recursion/recursion.sh +++ b/examples/recursion/recursion.sh @@ -1,2 +1,3 @@ $ go run recursion.go 5040 +13 diff --git a/public/recursion b/public/recursion index 28a9475..f218a05 100644 --- a/public/recursion +++ b/public/recursion @@ -43,7 +43,7 @@ Here’s a classic factorial example.
package main
fact(0)
.
func main() { fmt.Println(fact(7)) ++
Closures can also be recursive, but this requires the
+closure to be declared with a typed var
explicitly
+before it’s defined.
+ var fib func(n int) int ++
fib = func(n int) int { + if n < 2 { + return n + } + return fib(n-1) + fib(n-2) ++
Since fib
was previously declared in main
, Go
+knows which function to call with fib
here.
+ }
+
+ fmt.Println(fib(7)) }
fact(0)
.
$ go run recursion.go -5040+5040 +13
fact(0)
.