GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

No menu could be recovered. Follow the blue links in the page.

This view

  • Original page
  • New address

GeezerVison is showing gobyexample.com — Go by Example: Recursion

Go by Example: Recursion

Go supports recursive functions. Here’s a classic example.

package main
import "fmt"

This fact function calls itself until it reaches the base case of fact(0).

func fact(n int) int {
    if n == 0 {
        return 1
    }
    return n * fact(n-1)
}
func main() {
    fmt.Println(fact(7))

Anonymous functions can also be recursive, but this requires explicitly declaring a variable with var to store the function before it’s defined.

    var fib func(n int) int
    fib = func(n int) int {
        if n < 2 {
            return n
        }

Since fib was previously declared in main, Go knows which function to call with fib here.

        return fib(n-1) + fib(n-2)
    }
    fmt.Println(fib(7))
}
$ go run recursion.go 
5040
13

Next example: Range over Built-in Types.

by Mark McGranaghan and Eli Bendersky | source | license

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.