BlogJS BlogTwitter
Blog
JS Blog
Twitter

Recursion in Go

Golang Concepts

  • Hello World
  • Operators in Go
  • Declarations in Go
  • Values in Go
  • Variables in Go
  • For in Go
  • If/Else in Go
  • Switch in Go
  • Arrays in Go
  • Slices in Go
  • Maps in Go
  • Range in Go
  • Functions in Go
  • Closures in Go
  • Recursion in Go
  • Pointers in Go
  • Strings and Runes in Go
  • Structs in Go
  • Methods in Go
  • Interfaces in Go
  • Generics in Go
  • Errors in Go
  • Goroutines in Go
  • Channels in Go
  • Select in Go
  • Timeouts in Go
  • Timers in Go
  • Worker Pools in Go
  • WaitGroups in Go
  • Mutexes in Go
  • Sorting in Go
  • Panic in Go
  • Defer in Go
  • Recover in Go
  • JSON in Go
  • XML in Go
  • Time in Go
  • Epoch in Go
  • Time Formatting in Go
  • Random Numbers in Go
  • Number Parsing in Go
  • URL Parsing in Go
  • SHA256 Hashes in Go
  • Base64 Encoding in Go
  • Reading Files in Go
  • Writing Files in Go
  • File Paths in Go
  • Directories in Go
  • Testing and Benchmarking in Go
  • Command-Line Arguments in Go
  • Command-Line Flags in Go
  • Command-Line Subcommands in Go
  • Environment Variables in Go
  • HTTP Client in Go
  • HTTP Server in Go
  • Context in Go
  • Signals in Go

Go: Recursion

Go supports Recursion functions and it works similarly as how it works in other languages.


    package main
    import "fmt"

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

    //output
    //5040
    //13

Closures can also be recursive, but this requires the closure to be declared with a typed var explicitly before it’s defined.

Previous Article

Select in Go

Next Article

Recover in Go

LearnGolang

AboutPrivacyTerms & ConditionsContact us
Resources
All PostsCategoriesCode SnippetRoadmapInterview QuestionsJavaScript BlogCSS To Tailwind Converter
Other Link
Twitter
LearnGolangOnline
•
© 2023
•
All Right Reserved