Update Recursion example to demonstrate recursive closures

Fixes #389
This commit is contained in:
Eli Bendersky
2021-09-02 05:53:30 -07:00
parent 2acace92c0
commit d037acd3e6
4 changed files with 80 additions and 6 deletions

View File

@@ -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))
}