Go Tutorial
Go Useful Resources
Selected Reading
- Go - 错误处理
- Go - Interfaces
- Go - 类型转换
- Go - 递归
- Go - Maps
- Go - 范围
- Go - 切片
- Go - 结构
- Go - 指针
- Go - 数组
- Go - 字符串
- Go - 作用域
- Go - 函数
- Go - 循环
- Go - 条件判断
- Go - 操作符
- Go - 常量
- Go - 变量
- Go - 数据类型
- Go - 基本语法
- Go - 程序结构
- Go - 环境设置
- Go - 概述
- Go - Home
Go Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Go - 递归
Go - 递归
递归是以自相似的方式重复项目的过程。同样的概念也适用于编程语言。如果一个程序允许在同一个函数内调用一个函数,那么它被称为递归函数调用。看看下面的例子-
func recursion() { recursion() /* function calls itself */ } func main() { recursion() }
Go编程语言支持递归。也就是说,它允许函数调用自己。但是,在使用递归时,程序员需要小心地定义函数的退出条件,否则它将变成一个无限循环。
Examples of Recursion in Go
递归函数对于解决许多数学问题非常有用,例如计算数字的阶乘、生成斐波那契级数等。
Example 1: Calculating Factorial Using Recursion in Go
The following example calculates the factorial of a given number using a recursive function −
package main import "fmt" func factorial(i int)int { if(i <= 1) { return 1 } return i * factorial(i - 1) } func main() { var i int = 15 fmt.Printf("Factorial of %d is %d", i, factorial(i)) }
When the above code is compiled and executed, it produces the following result −
Factorial of 15 is 1307674368000
Example 2: Fibonacci Series Using Recursion in Go
下面的例子展示了如何使用递归函数−生成给定数字的斐波那契数列
package main import "fmt" func fibonaci(i int) (ret int) { if i == 0 { return 0 } if i == 1 { return 1 } return fibonaci(i-1) + fibonaci(i-2) } func main() { var i int for i = 0; i < 10; i++ { fmt.Printf("%d ", fibonaci(i)) } }
When the above code is compiled and executed, it produces the following result −
0 1 1 2 3 5 8 13 21 34