如何在Golang中建立簡單的遞迴函式?


在本教程中,我們將瞭解如何藉助演算法和示例在 Golang 中編寫簡單的遞迴函式。在第一個示例中,我們將按升序列印從 1 到 N 的數字,類似地,在另一個示例中,我們將按降序列印從 1 到 N 的數字。

在程式設計方面,如果我們在同一個函式中呼叫該函式並且有一個基本條件,則該函式是遞迴函式。每當滿足基本條件時,函式的呼叫就會停止,我們開始回滾到最後一步,即呼叫函式的地方。

語法

func functionName(arguments) returnType {

   // Base condition
   // Function calling according to the logic
}

示例 1

在本例中,我們將瞭解遞迴函式如何在 Golang 中按升序列印前 10 個數字。

package main
import (

   // fmt package provides the function to print anything
   "fmt"
)
func printAscendingOrder(number int) {

   // base condition of the function whenever the number becomes zero the function calls will stop
   if number == 0 {
      return
   }
   
   // calling the function within the function to make it recursive also, passing the number one lesser than the current value
   printAscendingOrder(number - 1)
   
   // printing the value of the number in
   // the current function calling the state
   fmt.Printf("%d ", number)
}
func main() {

   // declaring the variable
   var number int
   
   // initializing the variable
   number = 10
   fmt.Println("Golang program to print the number in ascending order with the help of a simple recursive function.")
   
   // calling the recursive function
   printAscendingOrder(number)
   fmt.Println()
}

輸出

Golang program to print the number in ascending order with the help of a simple recursive function.
1 2 3 4 5 6 7 8 9 10

示例 2

在本例中,我們將瞭解遞迴函式如何在 Golang 中按降序列印前 10 個數字。

package main
import (

   // fmt package provides the function to print anything
   "fmt"
)
func printDescendingOrder(number int) {

   // base condition of the function whenever the number becomes zero the function calls will stop
   if number == 0 {
      return
   }
   
   // printing the value of the number in the current function calling the state
   fmt.Printf("%d ", number)
   
   // calling the function within the function to make it recursive also, passing the number one lesser than the current value
   printDescendingOrder(number - 1)
}
func main() {

   // declaring the variable
   var number int
   
   // initializing the variable
   number = 10
   fmt.Println("Golang program to print the number in descending order with the help of a simple recursive function.")
   
   // calling the recursive function
   printDescendingOrder(number)
   fmt.Println()
}

輸出

Golang program to print the number in descending order with the help of a simple recursive function.
10 9 8 7 6 5 4 3 2 1

結論

這就是在 Golang 中建立簡單遞迴函式的方法,其中包含兩個示例,我們在其中按升序和降序列印了從 1 到 N 的數字。要了解有關 Golang 的更多資訊,您可以瀏覽這些教程。

更新於: 2023年1月11日

221 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告