Go - 函式閉包



Go 程式語言支援匿名函式,可作為函式閉包使用。在我們要在不傳遞任何名稱的情況下內聯定義函式時,使用匿名函式。

在我們的示例中,我們建立了一個名為 getSequence() 的函式,該函式返回另一個函式。此函式的目的是封閉上層函式的一個變數 i 以形成一個閉包。例如, −

package main

import "fmt"

func getSequence() func() int {
   i:=0
   return func() int {
      i+=1
      return i  
   }
}

func main(){
   /* nextNumber is now a function with i as 0 */
   nextNumber := getSequence()  

   /* invoke nextNumber to increase i by 1 and return the same */
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   
   /* create a new sequence and see the result, i is 0 again*/
   nextNumber1 := getSequence()  
   fmt.Println(nextNumber1())
   fmt.Println(nextNumber1())
}

當編譯並執行上述程式碼時,它會產生以下結果 −

1
2
3
1
2
go_functions.htm
廣告
© . All rights reserved.