Go Function recursion

Introduction

A function can call itself.

Here is one way to compute the factorial of a number:

func factorial(x uint) uint { 
    if x == 0 { 
        return 1 
    } 
    return x * factorial(x-1) 
} 

Usage


package main/* w  w  w  .jav  a 2s .  c om*/

import "fmt" 

func factorial(x uint) uint { 
    if x == 0 { 
        return 1 
    } 
    return x * factorial(x-1) 
} 

func main() { 
    fmt.Println(factorial(5))
} 



PreviousNext

Related