« Back to Index

Go: recursive function

View original Gist on GitHub

Tags: #go #recursive

recursion.go

package main

import (
	"fmt"
)

func recurse(n int) string {
	if n == 0 {
		return fmt.Sprintf("done: %d", n)
	}
	fmt.Println(n)
	return recurse(n - 1)
}

func main() {
	fmt.Println(recurse(3))
	fmt.Println(recurse(2))
	fmt.Println(recurse(1))
	fmt.Println(recurse(0))
}

// Here is a real world example using recursion to simplify the tree style traversal of a complex map.
//
// In this example `segs` is a slice of CLI arguments (e.g. `foo bar baz`) and we have a nested map data structure that's built around these arguments. We want to get to the nested map assigned to `baz`.
//
// NOTE: Each recursive call not only decrements the `n` counter but also removes the previous CLI arg so `segs` becomes shorter on each iteration.
func recurse(n int, segs []string, c commands) commands {
	if n == 0 {
		return c
	}
	data, ok := c[segs[0]]
	if ok {
		data, ok := data.(map[string]interface{})
		if ok {
			return recurse(n-1, segs[1:], data)
		}
	}
	return nil
}