- Go 教程
- Go - 主頁
- Go - 概覽
- Go - 環境設定
- Go - 程式結構
- Go - 基本語法
- Go - 資料型別
- Go - 變數
- Go - 常量
- Go - 運算子
- Go - 決策
- Go - 迴圈
- Go - 函式
- Go - 作用域規則
- Go - 字串
- Go - 陣列
- Go - 指標
- Go - 結構
- Go - 切片
- Go - 範圍
- Go - 對映
- Go - 遞迴
- Go - 型別轉換
- Go - 介面
- Go - 錯誤處理
- Go 有用資源
- Go - 問題和答案
- Go - 快速指南
- Go - 有用資源
- Go - 討論
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
廣告