Go language recursive function

Source: Internet
Author: User

Go language recursive function

Recursion is the invocation of yourself in the process of running.

The syntax format is as follows:

1 func recursion () {2    /*  */3}45func main () {6    Recursion ()7 }

The Go language supports recursion. But when we use recursion, the developer needs to set the exit criteria, or the recursion will fall into an infinite loop.

Recursive functions are useful for solving mathematical problems, like calculating factorial, generating Fibonacci sequences, and so on.

----------------------------------------------------------------------------------------------

Factorial

The following example uses the recursive function instance factorial of the Go language:

1 Package Main2 3Import"FMT"4 5Func factorial (xint) (Resultint) {6   ifx = =0 {7result =1; 8}Else {9result = x * factorial (X-1);Ten   } One   return; A } -  - Func Main () { the     varIint= the -Fmt. Printf ("the factorial of%d is%d\n", I, factorial (i)) -}

The output of the above instance execution is:

 the 1307674368000
Fibonacci sequence

The following example implements the Fibonacci sequence with the recursive function of the Go language:

1 Package Main2 3Import"FMT"4 5Func Fibonacci (nint)int {6   ifN <2 {7    returnN8   }9   returnFibonacci (n2) + Fibonacci (n1)Ten } One  A Func Main () { -     varIint -      fori =0; I <Ten; i++ { theFmt. Printf ("%d\t", Fibonacci (i)) -     } -}

The output of the above instance execution is:

0    1    1    2    3    5    8     -     +     the

Go language recursive function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.