Recursive Functions in Golang

GolangGolangBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This lab will test your understanding of recursive functions in Golang.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Golang`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go/FunctionsandControlFlowGroup -.-> go/recursion("`Recursion`") subgraph Lab Skills go/recursion -.-> lab-15501{{"`Recursive Functions in Golang`"}} end

Recursion

The sum function takes an integer slice and returns the sum of all the integers in the slice. However, the function is incomplete and needs to be implemented using recursion.

  • The sum function must be implemented using recursion.
  • The function must take an integer slice as input.
  • The function must return the sum of all the integers in the slice.
$ go run recursion.go
5040
13

There is the full code below:

// Go supports
// <a href="https://en.wikipedia.org/wiki/Recursion_(computer_science)"><em>recursive functions</em></a>.
// 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))

	// 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
		}

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

Summary

In this lab, you were tasked with implementing the sum function using recursion. Recursion is a powerful tool that can simplify complex problems by breaking them down into smaller sub-problems. By completing this lab, you should now have a better understanding of how to use recursion in Golang.

Other Golang Tutorials you may like